-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathjump_game_iv.cpp
47 lines (47 loc) · 882 Bytes
/
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
46
47
class Solution {
public:
int minJumps(vector<int>& arr)
{
unordered_map<int,vector<int>> adj;
int n=arr.size();
for(int i=0;i<n;++i)
if(adj.find(arr[i])==adj.end())
adj[arr[i]]={i};
else adj[arr[i]].push_back(i);
vector<int> grey(n,0);
grey[0]=1;
queue<pair<int,int>> q;
q.push({0,0});
int ret=INT_MAX;
while(!q.empty())
{
pair<int,int> temp=q.front();
q.pop();
int u=temp.first;
int d=temp.second;
if(u==n-1)
return d;
else
{
if(u>0&&!grey[u-1])
{
q.push({u-1,d+1});
grey[u-1]=1;
}
if(u+1<n&&!grey[u+1])
{
q.push({u+1,d+1});
grey[u+1]=1;
}
for(int v:adj[arr[u]])
if(!grey[v])
{
q.push({v,d+1});
grey[v]=1;
}
adj[arr[u]]={};
}
}
return ret;
}
};