File tree 1 file changed +34
-26
lines changed
Leetcode Daily Challenge/December-2020
1 file changed +34
-26
lines changed Original file line number Diff line number Diff line change @@ -52,54 +52,62 @@ class Solution
52
52
public:
53
53
int minJumps (vector<int > &arr)
54
54
{
55
- unordered_map<int , vector<int >> adj;
55
+ if (arr.size () == 1 )
56
+ return 0 ;
56
57
int n = arr.size ();
58
+ vector<int > visited (n, 0 );
57
59
60
+ unordered_map<int , vector<int >> adj;
58
61
for (int i = 0 ; i < n; ++i)
62
+ {
59
63
if (adj.find (arr[i]) == adj.end ())
60
64
adj[arr[i]] = {i};
61
65
else
62
66
adj[arr[i]].push_back (i);
67
+ }
63
68
64
- vector<int > grey (n, 0 );
65
- grey[0 ] = 1 ;
66
-
67
- queue<vector<int >> q;
68
- q.push ({0 , 0 });
69
- int ret = INT_MAX;
69
+ queue<int > q;
70
+ q.push (0 );
71
+ visited[0 ] = 1 ;
72
+ int ans = 0 ;
70
73
71
74
while (q.size ())
72
75
{
73
- auto temp = q.front ();
74
- q.pop ();
75
- int u = temp[0 ], d = temp[1 ];
76
- if (u == n - 1 )
77
- return d;
78
- else
76
+ int size = q.size ();
77
+ for (int i = 0 ; i < size; ++i)
79
78
{
80
- if (u > 0 && !grey[u - 1 ])
79
+ int idx = q.front ();
80
+ q.pop ();
81
+ if (idx == n - 1 )
82
+ return ans;
83
+
84
+ if (idx - 1 >= 0 && idx - 1 < n && visited[idx - 1 ] == 0 )
81
85
{
82
- q.push ({u - 1 , d + 1 } );
83
- grey[u - 1 ] = 1 ;
86
+ q.push (idx - 1 );
87
+ visited[idx - 1 ] = 1 ;
84
88
}
85
- if (u + 1 < n && !grey[u + 1 ])
89
+
90
+ if (idx + 1 >= 0 && idx + 1 < n && visited[idx + 1 ] == 0 )
86
91
{
87
- q.push ({u + 1 , d + 1 } );
88
- grey[u + 1 ] = 1 ;
92
+ q.push (idx + 1 );
93
+ visited[idx + 1 ] = 1 ;
89
94
}
90
95
91
- for ( int v : adj[ arr[u]] )
96
+ if ( adj. find ( arr[idx]) != adj. end () )
92
97
{
93
- if (!grey[v ])
98
+ for ( auto &i : adj[arr[idx] ])
94
99
{
95
- q.push ({v, d + 1 });
96
- grey[v] = 1 ;
100
+ if (visited[i] == 0 )
101
+ {
102
+ q.push (i);
103
+ visited[i] = 1 ;
104
+ }
97
105
}
106
+ adj.erase (arr[idx]);
98
107
}
99
- adj[arr[u]] = {};
100
108
}
109
+ ans++;
101
110
}
102
-
103
- return ret;
111
+ return ans;
104
112
}
105
113
};
You can’t perform that action at this time.
0 commit comments