Problem §
Examples §
Solutions §
from collections import deque
class Snake:
def __init__(self, width, height, food):
self.width = width;
self.height = height;
self.snake = deque([(0, 0)]);
self.snake_cells = set([(0, 0)]);
self.food = food;
self.current_food_idx = 0;
def get_next_cell(self, direction):
head = list(self.snake[0]).copy()
if direction == "U":
return (head[0], head[1] - 1)
elif direction == "D":
return (head[0], head[1] + 1)
elif direction == "R":
return (head[0] + 1, head[1])
else:
return (head[0] - 1, head[1])
def is_valid_cell(self, cell):
if cell in self.snake_cells:
return False
x, y = cell
if x < 0 or x >= self.width or y < 0 or y >= self.height:
return False
return True
def move(self, direction):
head = self.snake[0]
next_cell = self.get_next_cell(direction)
if not self.is_valid_cell(next_cell):
return -1
current_food = self.food[self.current_food_idx]
is_food = next_cell[0] == current_food[1] and next_cell[1] == current_food[0]
if not is_food:
popped = self.snake.pop()
self.snake_cells.remove(popped)
self.snake.appendleft(next_cell)
self.snake_cells.add(next_cell)
if is_food:
self.current_food_idx += 1
return len(self.snake) - 1