Check if a sequence of path visits any coordinate twice or not
Given string str of length N only consisting of characters ‘N’, ‘S’, ‘E’, or ‘W’, each representing moving one unit North, South, East, or West, respectively. A man starts at the origin (0, 0) on a 2D plane and walks according to the directions in the string. The task is to check whether the man crosses any coordinate in his walk, which he has already visited or not. If found to be true, then print “Crossed”. Otherwise, print “Not Crossed”.
Examples:
Input: str = “NESW”
Output: Crossed
Explanation:
The path for the man is given by:
(0, 0) -> (0, 1) -> (1, 1) -> (0, 1) -> (0, 0).
Since, the coordinate (0, 0) is visited again.
Therefore, print Crossed as he has crossed the path.
Input: str = “SESS”
Output: Not Crossed
Explanation:
The path for the man is given by:
(0, 0) -> (0, -1) -> (1, -1) -> (1, -2) -> (1, -3).
From the above path, the man never visited the same coordinate again.
Therefore, print Not Crossed.
Approach: The idea is to maintain a Set for the co-ordinates encountered to check whether already visited co-ordinates occurs or not. Below are the steps:
- Initialize two variables X and Y and initiate the values as zero. These variables will represent x and y coordinates.
- Insert X and Y in the set.
- Iterate a loop over the range [0, N), and increment the X or Y coordinate as per the below condition:
- If the character is ‘N’, then increment Y by 1.
- If the character is ‘S’, then decrement Y by 1.
- If the character is ‘E’, then increment X by 1.
- If the character is ‘W’, then decrement X by 1.
- Insert the updated X and Y coordinates in the above step for each character in the set.
- While inserting the co-ordinates in the above step if any present co-ordinates are encountered then print Crossed.
- Otherwise, print Not Crossed as all the points of co-ordinates are unique.
Below is the implementation of the above approach
C++
#include <bits/stdc++.h>
using namespace std;
bool isCrossed(string path)
{
if (path.size() == 0)
return false ;
bool ans = false ;
set<pair< int , int > > set;
int x = 0, y = 0;
set.insert({ x, y });
for ( int i = 0; i < path.size(); i++) {
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 });
if (set.find({ x, y })
!= set.end()) {
ans = true ;
break ;
}
}
if (ans)
cout << "Crossed" ;
else
cout << "Not Crossed" ;
}
int main()
{
string path = "NESW" ;
isCrossed(path);
return 0;
}
|
Java
import java.awt.Point;
import java.util.HashSet;
class GFG{
static void isCrossed(String path)
{
if (path.length() == 0 )
return ;
boolean ans = false ;
HashSet<Point> set =
new HashSet<Point>();
int x = 0 , y = 0 ;
set.add( new Point(x, y));
for ( int i = 0 ; i < path.length(); i++)
{
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));
if (set.contains( new Point(x, y)))
{
ans = true ;
break ;
}
}
if (ans)
System.out.print( "Crossed" );
else
System.out.print( "Not Crossed" );
}
public static void main(String[] args)
{
String path = "NESW" ;
isCrossed(path);
}
}
|
Python3
def isCrossed(path):
if ( len (path) = = 0 ):
return bool ( False )
ans = bool ( False )
Set = set ()
x, y = 0 , 0
Set .add((x, y))
for i in range ( len (path)):
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
if (x, y) in Set :
ans = bool ( True )
break
if (ans):
print ( "Crossed" )
else :
print ( "Not Crossed" )
path = "NESW"
isCrossed(path)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void isCrossed(String path)
{
if (path.Length == 0)
return ;
bool ans = false ;
HashSet<KeyValuePair< int , int >> mySet =
new HashSet<KeyValuePair< int , int >>();
int x = 0, y = 0;
mySet.Add( new KeyValuePair< int , int >(x, y));
for ( int i = 0; i < path.Length; i++)
{
if (path[i] == 'N' )
mySet.Add(
new KeyValuePair< int , int >(x, y++));
if (path[i] == 'S' )
mySet.Add(
new KeyValuePair< int , int >(x, y--));
if (path[i] == 'E' )
mySet.Add(
new KeyValuePair< int , int >(x++, y));
if (path[i] == 'W' )
mySet.Add(
new KeyValuePair< int , int >(x--, y));
if (mySet.Contains(
new KeyValuePair< int , int >(x, y)))
{
ans = true ;
break ;
}
}
if (ans)
Console.Write( "Crossed" );
else
Console.Write( "Not Crossed" );
}
public static void Main(String[] args)
{
String path = "NESW" ;
isCrossed(path);
}
}
|
Javascript
<script>
function isCrossed(path)
{
if (path.length == 0)
return ;
let ans = false ;
let mySet = new Set();
let x = 0, y = 0;
mySet.add([x, y]);
for (let i = 0; i < path.length; i++)
{
if (path[i] == 'N' )
mySet.add([x, y++]);
if (path[i] == 'S' )
mySet.add([x, y--]);
if (path[i] == 'E' )
mySet.add([x++, y]);
if (path[i] == 'W' )
mySet.add([x--, y]);
if (!mySet.has([x, y]))
{
ans = true ;
break ;
}
}
if (ans)
document.write( "Crossed" );
else
document.write( "Not Crossed" );
}
let path = "NESW" ;
isCrossed(path);
</script>
|
Time Complexity: O(N*log N)
Auxiliary Space: O(N)
Last Updated :
30 Sep, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...