*353. Design Snake Game
https://leetcode.com/problems/design-snake-game/
solution
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
self.width = width
self.height = height
self.food = collections.deque(food)
self.score = 0
self.snake = collections.deque([(0, 0)])
self.snake_positions = set([(0, 0)])
def move(self, direction: str) -> int:
head_row, head_col = self.snake[0]
if direction == 'U':
head_row -= 1
elif direction == 'D':
head_row += 1
elif direction == 'L':
head_col -= 1
elif direction == 'R':
head_col += 1
if head_row < 0 or head_row >= self.height or head_col < 0 or head_col >= self.width:
return -1
if self.food and [head_row, head_col] == self.food[0]:
self.food.popleft() # Eat the food
self.score += 1 # Increase the score
else:
tail = self.snake.pop()
self.snake_positions.remove(tail)
if (head_row, head_col) in self.snake_positions:
return -1
self.snake.appendleft((head_row, head_col))
self.snake_positions.add((head_row, head_col))
return self.score
时间复杂度:O() 空间复杂度:O()
Last updated