Count points which are revisited while following the path specified by a given string | Java program for the above approach ; 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
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int count ( String S , int X , int Y ) { int N = S . length ( ) ; int temp_x = 0 , temp_y = 0 ; int count = 0 ; HashSet < String > s = new HashSet < > ( ) ; s . add ( ( X + " # " + Y ) ) ; for ( int i = 0 ; i < N ; i ++ ) { temp_x = X ; temp_y = Y ; if ( S . charAt ( i ) == ' U ' ) { X ++ ; } else if ( S . charAt ( i ) == ' D ' ) { X -- ; } else if ( S . charAt ( i ) == ' R ' ) { Y ++ ; } else { Y -- ; } if ( s . contains ( ( temp_x + X ) + " # " + ( temp_y + Y ) ) ) { count ++ ; } else { s . add ( ( temp_x + X ) + " # " + ( temp_y + Y ) ) ; } } return count ; } public static void main ( String [ ] args ) { String S = " RDDUDL " ; int X = 0 , Y = 0 ; System . out . print ( count ( S , X , Y ) ) ; } }