-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.ts
63 lines (60 loc) · 1.54 KB
/
Solution.ts
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class SnakeGame {
private m: number;
private n: number;
private food: number[][];
private score: number;
private idx: number;
private q: number[];
private vis: Set<number>;
constructor(width: number, height: number, food: number[][]) {
this.m = height;
this.n = width;
this.food = food;
this.score = 0;
this.idx = 0;
this.q = [0];
this.vis = new Set([0]);
}
move(direction: string): number {
const p = this.q[0];
const i = Math.floor(p / this.n);
const j = p % this.n;
let x = i;
let y = j;
if (direction === 'U') {
--x;
} else if (direction === 'D') {
++x;
} else if (direction === 'L') {
--y;
} else {
++y;
}
if (x < 0 || x >= this.m || y < 0 || y >= this.n) {
return -1;
}
if (
this.idx < this.food.length &&
x === this.food[this.idx][0] &&
y === this.food[this.idx][1]
) {
++this.score;
++this.idx;
} else {
const t = this.q.pop()!;
this.vis.delete(t);
}
const cur = x * this.n + y;
if (this.vis.has(cur)) {
return -1;
}
this.q.unshift(cur);
this.vis.add(cur);
return this.score;
}
}
/**
* Your SnakeGame object will be instantiated and called as such:
* var obj = new SnakeGame(width, height, food)
* var param_1 = obj.move(direction)
*/