text: Check if a sequence of path visits any coordinate twice or not | Java 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: 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 ) ; } }