Clean python solution


  • 0
    R
    class SnakeGame(object):
    
        def __init__(self, width,height,food):
            """
            Initialize your data structure here.
            @param width - screen width
            @param height - screen height 
            @param food - A list of food positions
            E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].
            :type width: int
            :type height: int
            :type food: List[List[int]]
            """
            self.width = width
            self.height = height
            self.curPos = (0, 0)
            self.food = food[::-1]
            self.path = [(0, 0)] # deque might be better
            self.pathSet = set([(0, 0)])
    
        def move(self, direction):
            """
            Moves the snake.
            @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down 
            @return The game's score after the move. Return -1 if game over. 
            Game over when snake crosses the screen boundary or bites its body.
            :type direction: str
            :rtype: int
            """
            i, j = self.curPos
            
            if direction == "U":
                i -= 1
            
            if direction == "L":
                j -= 1
            
            if direction == "R":
                j += 1
                
            if direction == "D":
                i += 1
                
            if i < 0 or i >= self.height or j < 0 or j >= self.width:
                return -1
    
            lastPath = self.path.pop()
            self.pathSet.remove(lastPath)
            
            if (i, j) in self.pathSet:
                return -1
            
            self.path.insert(0,(i, j))
            self.pathSet.add((i, j))
            self.curPos = (i, j)
            
            if self.food and self.food[-1][0] == self.curPos[0] and self.food[-1][1] == self.curPos[1]:
                self.food.pop()
                self.path.append(lastPath)
                self.pathSet.add(lastPath)
                
            return len(self.path) - 1

  • 0
    C

    there would be a bug if new head == lastPath and food[-1] == lastPath


Log in to reply
 

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