-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path64_jumpgameIV.cpp
More file actions
48 lines (45 loc) · 1.37 KB
/
64_jumpgameIV.cpp
File metadata and controls
48 lines (45 loc) · 1.37 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
//https://leetcode.com/problems/jump-game-iv/description/
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<int>q;
vector<bool>visited(n, false);
q.push(0);
int steps = 0;
while(!q.empty())
{
int size = q.size();
while(size--)
{
int currIdx = q.front();
q.pop();
if (currIdx == n - 1) return steps;
if (currIdx + 1 < n && !visited[currIdx + 1])
{
visited[currIdx + 1] = true;
q.push(currIdx + 1);
}
if (currIdx - 1 >= 0 && !visited[currIdx - 1])
{
visited[currIdx - 1] = true;
q.push(currIdx - 1);
}
for (int newIdx : mp[arr[currIdx]])
{
if (!visited[newIdx])
{
visited[newIdx] = true;
q.push(newIdx);
}
}
mp[arr[currIdx]].clear();
}
steps++;
}
return -1;
}
};