📌  相关文章
📜  检查路径序列是否两次访问任何坐标

📅  最后修改于: 2021-04-27 05:43:26             🧑  作者: Mango

给定长度为N的字符串str ,该字符串仅由字符‘N’,’S’,’E’‘W’组成,每个字符分别表示分别向北,向南,向东向西移动一个单位。一个人从2D平面上的原点(0,0)开始,然后按照字符串的方向行走。任务是检查该人是否已走过他走过的任何坐标。如果发现是正确的,则打印“划线” 。否则,请打印“ Not Crossed”

例子:

方法:想法是为遇到的坐标维护一个Set ,以检查是否已经访问过的坐标。步骤如下:

  1. 初始化两个变量XY并将值初始化为零。这些变量将代表xy坐标。
  2. 在集合中插入XY。
  3. [0,N)范围内循环循环,并根据以下条件递增X或Y坐标:
    • 如果字符为“ N” ,则将Y递增1
    • 如果字符为“ S” ,则将Y1
    • 如果字符为“ E” ,则将X递增1
    • 如果字符为“ W” ,则将X1
  4. 在上述步骤中,为集合中的每个字符插入更新的XY坐标。
  5. 在上述步骤中插入坐标时,如果遇到任何当前坐标,则打印Crossed
  6. 否则,打印“不交叉”,因为所有坐标点都是唯一的。

下面是上述方法的实现

C++
// C++ program for the above appproach
 
#include 
using namespace std;
 
// Function to check if the man crosses
// previous visited coordinate or not
bool isCrossed(string path)
{
    if (path.size() == 0)
        return false;
 
    // Stores the count of
    // crossed vertex
    bool ans = false;
 
    // Stores (x, y) coordinates
    set > set;
 
    // The coordinates for the origin
    int x = 0, y = 0;
    set.insert({ x, y });
 
    // Iterate over the string
    for (int i = 0; i < path.size(); i++) {
 
        // Condition to increment X or
        // Y co-ordinates respectively
        if (path[i] == 'N')
            set.insert({ x, y++ });
 
        if (path[i] == 'S')
            set.insert({ x, y-- });
 
        if (path[i] == 'E')
            set.insert({ x++, y });
 
        if (path[i] == 'W')
            set.insert({ x--, y });
 
        // Check if (x, y) is already
        // visited
        if (set.find({ x, y })
            != set.end()) {
 
            ans = true;
            break;
        }
    }
 
    // Print the result
    if (ans)
        cout << "Crossed";
    else
        cout << "Not Crossed";
}
 
// Driver Code
int main()
{
    // Given string
    string path = "NESW";
 
    // Function Call
    isCrossed(path);
 
    return 0;
}


Java
// Java program for
// the above appproach
import java.awt.Point;
import java.util.HashSet;
class GFG{
 
// Function to check if the man crosses
// previous visited coordinate or not
static void isCrossed(String path)
{
  if (path.length() == 0)
    return;
 
  // Stores the count of
  // crossed vertex
  boolean ans = false;
 
  // Stores (x, y) coordinates
  HashSet set =
          new HashSet();
 
  // The coordinates for the origin
  int x = 0, y = 0;
  set.add(new Point(x, y));
 
  // Iterate over the String
  for (int i = 0; i < path.length(); i++)
  {
    // Condition to increment X or
    // Y co-ordinates respectively
    if (path.charAt(i) == 'N')
      set.add(new Point(x, y++));
 
    if (path.charAt(i) == 'S')
      set.add(new Point(x, y--));
 
    if (path.charAt(i) == 'E')
      set.add(new Point(x++, y));
 
    if (path.charAt(i) == 'W')
      set.add(new Point(x--, y));
 
    // Check if (x, y) is already
    // visited
    if (set.contains(new Point(x, y)))
    {
      ans = true;
      break;
    }
  }
 
  // Print the result
  if (ans)
    System.out.print("Crossed");
  else
    System.out.print("Not Crossed");
}
 
// Driver Code
public static void main(String[] args)
{
  // Given String
  String path = "NESW";
 
  // Function Call
  isCrossed(path);
}
}
 
// This code is contributed by Princi Singh


Python3
# Python3 program for the above appproach
 
# Function to check if the man crosses
# previous visited coordinate or not
def isCrossed(path):
 
    if (len(path) == 0):
        return bool(False)
 
    # Stores the count of
    # crossed vertex
    ans = bool(False)
 
    # Stores (x, y) coordinates
    Set = set()
 
    # The coordinates for the origin
    x, y = 0, 0
    Set.add((x, y))
 
    # Iterate over the string
    for i in range(len(path)):
 
        # Condition to increment X or
        # Y co-ordinates respectively
        if (path[i] == 'N'):
            Set.add((x, y))
            y = y + 1
 
        if (path[i] == 'S'):
            Set.add((x, y))
            y = y - 1
             
        if (path[i] == 'E'):
            Set.add((x, y))
            x = x + 1
 
        if (path[i] == 'W'):
            Set.add((x, y))
            x = x - 1
             
        # Check if (x, y) is already visited
        if (x, y) in Set:
            ans = bool(True)
            break
 
    # Print the result
    if (ans):
        print("Crossed")
    else:
        print("Not Crossed")
 
# Driver code
 
# Given string
path = "NESW"
 
# Function call
isCrossed(path)
 
# This code is contributed by divyeshrabadiya07


C#
// C# program for the above appproach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to check if the man crosses
// previous visited coordinate or not
static void isCrossed(String path)
{
    if (path.Length == 0)
        return;
 
    // Stores the count of
    // crossed vertex
    bool ans = false;
 
    // Stores (x, y) coordinates
    HashSet> mySet =
    new HashSet>();
 
    // The coordinates for the origin
    int x = 0, y = 0;
    mySet.Add(new KeyValuePair(x, y));
 
    // Iterate over the String
    for(int i = 0; i < path.Length; i++)
    {
         
        // Condition to increment X or
        // Y co-ordinates respectively
        if (path[i] == 'N')
            mySet.Add(
                new KeyValuePair(x, y++));
 
        if (path[i] == 'S')
            mySet.Add(
                new KeyValuePair(x, y--));
 
        if (path[i] == 'E')
            mySet.Add(
                new KeyValuePair(x++, y));
 
        if (path[i] == 'W')
            mySet.Add(
                new KeyValuePair(x--, y));
 
        // Check if (x, y) is already
        // visited
        if (mySet.Contains(
                new KeyValuePair(x, y)))
        {
            ans = true;
            break;
        }
    }
 
    // Print the result
    if (ans)
        Console.Write("Crossed");
    else
        Console.Write("Not Crossed");
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given String
    String path = "NESW";
 
    // Function call
    isCrossed(path);
}
}
 
// This code is contributed by akhilsaini


输出:
Crossed







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