Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- int minJumps(vector<int>& arr) {
- int n = arr.size();
- unordered_map<int, vector<int>> indicesOfValue;
- for (int i = 0; i < n; i++)
- indicesOfValue[arr[i]].push_back(i);
- vector<bool> visited(n); visited[0] = true;
- queue<int> q; q.push(0);
- int step = 0;
- while (!q.empty()) {
- int sz = q.size();
- while(sz--) {
- int i = q.front(); q.pop();
- if (i == n - 1) return step; // Reached to last index
- if(i-1 >= 0 && !visited[i-1]){
- q.push(i-1);
- visited[i-1] = true;
- }
- if(i+1 < n && !visited[i+1]){
- q.push(i+1);
- visited[i+1] = true;
- }
- for(int j:indicesOfValue[arr[i]]) {
- if(j >= 0 && j < n && !visited[j]) {
- visited[j] = true;
- q.push(j);
- }
- }
- // Very important step to clear the array, else will get TLE.
- indicesOfValue[arr[i]].clear();
- }
- step++;
- }
- return 0;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement