Count points which are revisited while following the path specified by a given string | Function to find the number of times already visited position is revisited after starting traversal from { X , Y } ; Stores the x and y temporarily ; Stores the number of times an already visited position is revisited ; Initialize hashset ; Insert the starting coordinates ; Traverse over the string ; Update the coordinates according to the current directions ; If the new { X , Y } has been visited before , then increment the count by 1 ; Otherwise ; Insert new { x , y } ; Driver Code
function count ( S , X , Y ) { let N = S . length ; let temp_x = 0 , temp_y = 0 ; let count = 0 ; let s = new Set ( ) ; s . add ( ( X + " " + Y ) ) ; for ( let i = 0 ; i < N ; i ++ ) { temp_x = X ; temp_y = Y ; if ( S [ i ] == ' ' ) { X ++ ; } else if ( S [ i ] == ' ' ) { X -- ; } else if ( S [ i ] == ' ' ) { Y ++ ; } else { Y -- ; } if ( s . has ( ( temp_x + X ) + " " + ( temp_y + Y ) ) ) { count ++ ; } else { s . add ( ( temp_x + X ) + " " + ( temp_y + Y ) ) ; } } return count ; } let S = " " ; let X = 0 , Y = 0 ; document . write ( count ( S , X , Y ) ) ;