text: Check if a sequence of path visits any coordinate twice or not | C ++ program for the above approach ; Function to check if the man crosses previous visited coordinate or not ; Stores the count of crossed vertex ; Stores ( x , y ) coordinates ; The coordinates for the origin ; Iterate over the string ; Condition to increment X or Y co - ordinates respectively ; Check if ( x , y ) is already visited ; Print the result ; Driver Code ; Given string ; Function Call
code: #include <bits/stdc++.h> NEW_LINE 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 ; }