-
Notifications
You must be signed in to change notification settings - Fork 12
/
1345. Jump Game IV 5 th march
54 lines (45 loc) · 1.25 KB
/
1345. Jump Game IV 5 th march
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
50
51
52
53
54
class Solution
{
public:
int minJumps(vector<int> &arr)
{
int n = arr.size();
const int inf = 1e9;
unordered_map<int, vector<int>> mp;
for (int i = 0; i < n; i++)
mp[arr[i]].push_back(i);
queue<pair<int, int>> q;
q.push({0, 0});
vector<int> dist(n, inf);
dist[0] = 0;
while (!q.empty())
{
auto idx = q.front().first;
auto moves = q.front().second;
q.pop();
assert(idx >= 0 and idx < n);
if (idx == n - 1)
return moves;
if (idx - 1 >= 0 and moves + 1 < dist[idx - 1])
{
dist[idx - 1] = moves + 1;
q.push({idx - 1, moves + 1});
}
if (idx + 1 < n and moves + 1 < dist[idx + 1])
{
dist[idx + 1] = moves + 1;
q.push({idx + 1, moves + 1});
}
for (auto i : mp[arr[idx]])
{
if (i != idx and moves + 1 < dist[i])
{
dist[i] = moves + 1;
q.push({i, moves + 1});
}
}
mp.erase(arr[idx]);
}
return -1;
}
};