OOP solution using coordinate for position(python)


  • 0
    W

    This is a simple version of the Random Walk problem. You need (x,y) to represent the position of the walker in the constructor(just like init in python), a move() method to represent one move, each move you change the position of the walker according to the direction. In the judgeCircle() method you analyze how many moves that have been taken, call the move() method, and after that you can compare it with the original position (0,0) and get the answer.

    class Solution:
        
        def judgeCircle(self, moves):
            """
            :type moves: str
            :rtype: bool
            """
            for i in moves:
                self.move(i)
            if (self.x,self.y)==(0,0):
                return True
            else:
                return False
        def __init__(self):
            self.x=0
            self.y=0
        def move(self,direction):
            if direction=='U':
                self.y+=1
            elif direction=='D':
                self.y-=1
            elif direction=='L':
                self.x-=1
            elif direction=='R':
                self.x+=1
            else:
                print('invalid direction')
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.