📌  相关文章
📜  计算沿给定字符串指定的路径时重新访问的点

📅  最后修改于: 2021-04-18 02:34:20             🧑  作者: Mango

给定一个表示移动序列( LRUD )的字符串S以及两个表示起始坐标的整数XY ,任务是在遵循给定指定方向的情况下找到要重新访问的位置数根据以下规则的字符串:

  • 如果当前字符为L ,则将x坐标减1
  • 如果当前字符是R ,则将x坐标增加1
  • 如果当前字符是U ,则将y坐标增加1
  • 如果当前字符为D ,则将y坐标减1

例子:

方法:按照给定的步骤解决问题:

  • 初始化一个HashSet对,该对HashSet存储在遍历给定字符串和HashSet中的当前坐标时访问的一对坐标。
  • 遍历给定的字符串S并执行以下步骤:
    • 根据给定规则更新坐标{X,Y}的值。
    • 检查HashSet中是否存在更新的坐标。如果发现是正确的,则将计数1 ,。否则继续。
  • 完成上述步骤后,打印count的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the number of times
// already visited position is revisited
// after starting traversal from {X, Y}
int count(string S, int X, int Y)
{
    int N = S.length();
 
    // Stores the x and y temporarily
    int temp_x = 0, temp_y = 0;
 
    // Stores the number of times an
    // already visited position
    // is revisited
    int count = 0;
 
    // Initialize hashset
    set > s;
 
    // Insert the starting coordinates
    s.insert({ X, Y });
 
    // Traverse over the string
    for (int i = 0; i < N; i++) {
        temp_x = X;
        temp_y = Y;
 
        // Update the coordinates according
        // to the current directions
        if (S[i] == 'U') {
            X++;
        }
        else if (S[i] == 'D') {
            X--;
        }
        else if (S[i] == 'R') {
            Y++;
        }
        else {
            Y--;
        }
 
        // If the new {X, Y} has been
        // visited before, then
        // increment the count by 1
        if (s.find({ temp_x + X, temp_y + Y })
            != s.end()) {
            count++;
        }
 
        // Otherwise
        else {
 
            // Insert new {x, y}
            s.insert({ temp_x + X,
                       temp_y + Y });
        }
    }
 
    return count;
}
 
// Driver Code
int main()
{
    string S = "RDDUDL";
    int X = 0, Y = 0;
    cout << count(S, X, Y);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG
{
 
  // Function to find the number of times
  // already visited position is revisited
  // after starting traversal from {X, Y}
  static int count(String S, int X, int Y)
  {
    int N = S.length();
 
    // Stores the x and y temporarily
    int temp_x = 0, temp_y = 0;
 
    // Stores the number of times an
    // already visited position
    // is revisited
    int count = 0;
 
    // Initialize hashset
    HashSet s = new HashSet<>();
 
    // Insert the starting coordinates
    s.add((X + "#" + Y));
 
    // Traverse over the string
    for (int i = 0; i < N; i++) {
      temp_x = X;
      temp_y = Y;
 
      // Update the coordinates according
      // to the current directions
      if (S.charAt(i) == 'U') {
        X++;
      }
      else if (S.charAt(i) == 'D') {
        X--;
      }
      else if (S.charAt(i) == 'R') {
        Y++;
      }
      else {
        Y--;
      }
 
      // If the new {X, Y} has been
      // visited before, then
      // increment the count by 1
      if (s.contains((temp_x + X) + "#"
                     + (temp_y + Y))) {
        count++;
      }
 
      // Otherwise
      else {
 
        // Insert new {x, y}
        s.add((temp_x + X) + "#" + (temp_y + Y));
      }
    }
 
    return count;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
 
    String S = "RDDUDL";
    int X = 0, Y = 0;
    System.out.print(count(S, X, Y));
  }
}
 
// This code is contributed by Kingash.


Python3
# Python3 program for the above approach
 
# Function to find the number of times
# already visited position is revisited
# after starting traversal from {X, Y}
def count(S, X, Y):
    N = len(S)
 
    # Stores the x and y temporarily
    temp_x, temp_y = 0, 0
 
    # Stores the number of times an
    # already visited position
    # is revisited
    count = 0
 
    # Initialize hashset
    s = {}
 
    # Insert the starting coordinates
    s[(X, Y)] = 1
 
    # Traverse over the string
    for i in range(N):
        temp_x = X
        temp_y = Y
 
        # Update the coordinates according
        # to the current directions
        if (S[i] == 'U'):
            X += 1
        elif (S[i] == 'D'):
            X -= 1
        elif (S[i] == 'R'):
            Y += 1
        else:
            Y -= 1
 
        # If the new {X, Y} has been
        # visited before, then
        # increment the count by 1
        if ((temp_x + X, temp_y + Y ) in s):
            count += 1
        # Otherwise
        else:
            # Insert new {x, y}
            s[(temp_x + X,temp_y + Y )] = 1
    return count
 
# Driver Code
if __name__ == '__main__':
    S = "RDDUDL"
    X,Y = 0, 0
    print (count(S, X, Y))
 
    # This code is contributed by mohit kumar 29.


输出:
2

时间复杂度: O(N * log N)
辅助空间: O(N)