-
Notifications
You must be signed in to change notification settings - Fork 481
/
Copy path1345.cpp
49 lines (43 loc) · 1.22 KB
/
1345.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
48
49
class Solution
{
public:
int minJumps(vector<int>& arr)
{
unordered_map<int, vector<int>> g;
unordered_set<int> values;
int n = arr.size(), step = 0;
for (int i = 0; i < n; i++) g[arr[i]].push_back(i);
int vis[n] = {};
vis[0] = 1;
queue<int> q;
q.push(0);
while (!q.empty())
{
int k = q.size();
while (k--)
{
int pre = q.front(); q.pop();
if (pre == n - 1) return step;
if (pre - 1 >= 0 && !vis[pre - 1])
{
vis[pre - 1] = 1; q.push(pre - 1);
}
if (pre + 1 < n && !vis[pre + 1])
{
vis[pre + 1] = 1; q.push(pre + 1);
}
if (values.count(arr[pre])) continue;
values.insert(arr[pre]);
for (int i : g[arr[pre]])
{
if (!vis[i])
{
vis[i] = 1; q.push(i);
}
}
}
step++;
}
return step;
}
};