-
Notifications
You must be signed in to change notification settings - Fork 0
/
Jump game IV(Leetcode).cpp
54 lines (47 loc) · 1.39 KB
/
Jump game IV(Leetcode).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
class Solution {
public:
int minJumps(vector<int>& arr) {
int n = arr.size();
vector<vector<int>> graph(n);
unordered_map<int, vector<int>> sameVals;
for (int i = 0; i < n; i++) {
if (i - 1 >= 0) {
graph[i].emplace_back(i - 1);
}
if (i + 1 < n) {
graph[i].emplace_back(i + 1);
}
sameVals[arr[i]].emplace_back(i);
}
queue<int> q;
set<int> visited;
q.push(0);
visited.insert(0);
int cnt = 0;
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
int top = q.front();
q.pop();
if (top == n - 1) {
return cnt;
}
for (auto neigh:graph[top]) {
if (visited.find(neigh) == visited.end()) {
q.push(neigh);
visited.insert(neigh);
}
}
for (auto neigh:sameVals[arr[top]]) {
if (visited.find(neigh) == visited.end()) {
q.push(neigh);
visited.insert(neigh);
}
}
sameVals[arr[top]].clear();
}
cnt++;
}
return -1;
}
};