-
Notifications
You must be signed in to change notification settings - Fork 3
/
1345.cpp
45 lines (43 loc) · 1.34 KB
/
1345.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
class Solution {
public:
int minJumps(vector<int>& arr) {
unordered_map<int, vector<int>> mp;
unordered_map<int, bool> mpUsed;
int n = arr.size();
for (int i = 0; i < n; ++i) {
mp[arr[i]].push_back(i);
mpUsed[arr[i]] = false;
}
vector<bool> visited(n, false);
queue<int> q;
q.push(0);
visited[0] = true;
int step = 0;
while (!q.empty()) {
int m = q.size();
for (int i = 0; i < m; ++i) {
int node = q.front();
q.pop();
if (node == n - 1) return step;
if (node - 1 >= 0 && !visited[node - 1]) {
q.push(node - 1);
visited[node - 1] = true;
}
if (node + 1 < n && !visited[node + 1]) {
q.push(node + 1);
visited[node + 1] = true;
}
if (!mpUsed[arr[node]]) {
mpUsed[arr[node]] = true;
for (auto& neighbor : mp[arr[node]]) {
if (visited[neighbor]) continue;
q.push(neighbor);
visited[neighbor] = true;
}
}
}
step++;
}
return -1;
}
};