-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1345.cpp
More file actions
52 lines (40 loc) · 1.12 KB
/
Copy path1345.cpp
File metadata and controls
52 lines (40 loc) · 1.12 KB
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
// Jump game IV
// HARD
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int minJumps(vector<int>& arr) {
int n = arr.size();
unordered_map<int, vector<int>> mp;
for (int i = 0; i < n; i ++) {
mp[arr[i]].push_back(i);
}
queue<pair<int, int>> q;
q.push({0, 0});
vector<bool> visited(n, false);
visited[0] = true;
while(!q.empty()) {
auto [idx, lvl] = q.front(); q.pop();
if (idx == n - 1) return lvl;
int l = idx - 1;
if (l >= 0 && !visited[l]) {
visited[l] = true;
q.push({l, lvl + 1});
}
int r = idx + 1;
if (r < n && !visited[r]) {
visited[r] = true;
q.push({r, lvl + 1});
}
for (int nextIdx : mp[arr[idx]]) {
if (!visited[nextIdx]) {
visited[nextIdx] = true;
q.push({nextIdx, lvl + 1});
}
}
mp[arr[idx]].clear();
}
return -1;
}
};