-
Notifications
You must be signed in to change notification settings - Fork 0
/
1345-jump-game-iv.cpp
45 lines (40 loc) · 1.26 KB
/
1345-jump-game-iv.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) {
int n=arr.size();
unordered_map<int, vector<int>> mp;
// store indexes of intergers that equal
for(int i=0; i<n; i++)
mp[arr[i]].push_back(i);
int steps = 0;
queue<int> q;
vector<int> visited(n, 0);
q.push(0);
while(!q.empty()){
int size = q.size();
while(size--){
int currInd = q.front();
q.pop();
if(currInd == n-1) return steps;
if(currInd < n-1 && !visited[currInd + 1]){
visited[currInd + 1] = 1;
q.push(currInd + 1);
}
if(currInd - 1 >= 0 && !visited[currInd - 1]){
visited[currInd - 1] = 1;
q.push(currInd - 1);
}
for(int x : mp[arr[currInd]])
if(!visited[x]){
visited[x] = 1;
q.push(x);
}
mp[arr[currInd]].clear();
// because all num equals to num with
// curr index is pushed into queue
}
steps++;
}
return -1;
}
};