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
def count ( S , X , Y ) : NEW_LINE INDENT N = len ( S ) NEW_LINE temp_x , temp_y = 0 , 0 NEW_LINE count = 0 NEW_LINE s = { } NEW_LINE s [ ( X , Y ) ] = 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT temp_x = X NEW_LINE temp_y = Y NEW_LINE if ( S [ i ] == ' U ' ) : NEW_LINE INDENT X += 1 NEW_LINE DEDENT elif ( S [ i ] == ' D ' ) : NEW_LINE INDENT X -= 1 NEW_LINE DEDENT elif ( S [ i ] == ' R ' ) : NEW_LINE INDENT Y += 1 NEW_LINE DEDENT else : NEW_LINE INDENT Y -= 1 NEW_LINE DEDENT if ( ( temp_x + X , temp_y + Y ) in s ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT s [ ( temp_x + X , temp_y + Y ) ] = 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " RDDUDL " NEW_LINE X , Y = 0 , 0 NEW_LINE print ( count ( S , X , Y ) ) NEW_LINE DEDENT