-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.cpp
64 lines (60 loc) · 1.45 KB
/
Solution.cpp
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
64
class SnakeGame {
public:
SnakeGame(int width, int height, vector<vector<int>>& food) {
m = height;
n = width;
this->food = food;
score = 0;
idx = 0;
q.push_back(0);
vis.insert(0);
}
int move(string direction) {
int p = q.front();
int i = p / n, j = p % n;
int x = i, y = j;
if (direction == "U") {
--x;
} else if (direction == "D") {
++x;
} else if (direction == "L") {
--y;
} else {
++y;
}
if (x < 0 || x >= m || y < 0 || y >= n) {
return -1;
}
if (idx < food.size() && x == food[idx][0] && y == food[idx][1]) {
++score;
++idx;
} else {
int tail = q.back();
q.pop_back();
vis.erase(tail);
}
int cur = f(x, y);
if (vis.count(cur)) {
return -1;
}
q.push_front(cur);
vis.insert(cur);
return score;
}
private:
int m;
int n;
vector<vector<int>> food;
int score;
int idx;
deque<int> q;
unordered_set<int> vis;
int f(int i, int j) {
return i * n + j;
}
};
/**
* Your SnakeGame object will be instantiated and called as such:
* SnakeGame* obj = new SnakeGame(width, height, food);
* int param_1 = obj->move(direction);
*/