forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.py
43 lines (40 loc) · 1.15 KB
/
Solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
self.m = height
self.n = width
self.food = food
self.score = 0
self.idx = 0
self.q = deque([(0, 0)])
self.vis = {(0, 0)}
def move(self, direction: str) -> int:
i, j = self.q[0]
x, y = i, j
match direction:
case "U":
x -= 1
case "D":
x += 1
case "L":
y -= 1
case "R":
y += 1
if x < 0 or x >= self.m or y < 0 or y >= self.n:
return -1
if (
self.idx < len(self.food)
and x == self.food[self.idx][0]
and y == self.food[self.idx][1]
):
self.score += 1
self.idx += 1
else:
self.vis.remove(self.q.pop())
if (x, y) in self.vis:
return -1
self.q.appendleft((x, y))
self.vis.add((x, y))
return self.score
# Your SnakeGame object will be instantiated and called as such:
# obj = SnakeGame(width, height, food)
# param_1 = obj.move(direction)