File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ int minJumps (vector<int >& arr)
4
+ {
5
+ unordered_map<int ,vector<int >> adj;
6
+ int n=arr.size ();
7
+ for (int i=0 ;i<n;++i)
8
+ if (adj.find (arr[i])==adj.end ())
9
+ adj[arr[i]]={i};
10
+ else adj[arr[i]].push_back (i);
11
+ vector<int > grey (n,0 );
12
+ grey[0 ]=1 ;
13
+ queue<pair<int ,int >> q;
14
+ q.push ({0 ,0 });
15
+ int ret=INT_MAX;
16
+ while (!q.empty ())
17
+ {
18
+ pair<int ,int > temp=q.front ();
19
+ q.pop ();
20
+ int u=temp.first ;
21
+ int d=temp.second ;
22
+ if (u==n-1 )
23
+ return d;
24
+ else
25
+ {
26
+ if (u>0 &&!grey[u-1 ])
27
+ {
28
+ q.push ({u-1 ,d+1 });
29
+ grey[u-1 ]=1 ;
30
+ }
31
+ if (u+1 <n&&!grey[u+1 ])
32
+ {
33
+ q.push ({u+1 ,d+1 });
34
+ grey[u+1 ]=1 ;
35
+ }
36
+ for (int v:adj[arr[u]])
37
+ if (!grey[v])
38
+ {
39
+ q.push ({v,d+1 });
40
+ grey[v]=1 ;
41
+ }
42
+ adj[arr[u]]={};
43
+ }
44
+ }
45
+ return ret;
46
+ }
47
+ };
You can’t perform that action at this time.
0 commit comments