forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
57 lines (45 loc) · 1.33 KB
/
main.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
50
51
52
53
54
55
56
57
/// Source : https://leetcode.com/problems/jump-game-iv/
/// Author : liuyubobobo
/// Time : 2017-05-05
#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <queue>
using namespace std;
/// BFS
/// Time Complexity: O(n + m)
/// Space Complexity: O(n)
class Solution {
public:
int minJumps(vector<int>& arr) {
if(arr.size() == 1) return 0;
map<int, vector<int>> pos;
for(int i = 0; i < arr.size(); i ++)
pos[arr[i]].push_back(i);
vector<int> step(arr.size(), -1);
queue<int> q;
q.push(0);
step[0] = 0;
while(!q.empty()){
int cur = q.front();
q.pop();
if(cur == arr.size() - 1) return step[cur];
if(cur - 1 >= 0 && step[cur - 1] == -1)
q.push(cur - 1), step[cur - 1] = step[cur] + 1;
if(cur + 1 < arr.size() && step[cur + 1] == -1)
q.push(cur + 1), step[cur + 1] = step[cur] + 1;
for(int p: pos[arr[cur]])
if((p < cur - 1 || p > cur + 1) && step[p] == -1)
q.push(p), step[p] = step[cur] + 1;
pos.erase(arr[cur]);
}
return -1;
}
};
int main() {
vector<int> arr1 = {100,-23,-23,404,100,23,23,23,3,404};
cout << Solution().minJumps(arr1) << endl;
// 3
return 0;
}