Count points which are revisited while following the path specified by a given string | C # 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
using System ; using System . Collections . Generic ; public 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 < String > ( ) ; s . Add ( ( X + " # " + Y ) ) ; for ( int i = 0 ; i < N ; i ++ ) { temp_x = X ; temp_y = Y ; if ( S [ i ] == ' U ' ) { X ++ ; } else if ( S [ i ] == ' D ' ) { X -- ; } else if ( S [ 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 ; Console . Write ( count ( S , X , Y ) ) ; } }