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>> idx_of_same_val;
- for(int i = 0; i < n; i++){
- idx_of_same_val[arr[i]].push_back(i);
- }
- queue<int> q;
- vector<bool> visited(n, false);
- q.push(0);
- visited[0] = true;
- int steps = 0;
- while(!q.empty()){
- int qsize = q.size();
- for(int i = 0; i < qsize; i++){
- int t = q.front();
- q.pop();
- if(t == n - 1) return steps;
- if(t + 1 < n && !visited[t + 1]){
- q.push(t + 1);
- visited[t + 1] = true;
- }
- if(t - 1 >= 0 && !visited[t - 1]){
- q.push( t - 1 );
- visited[t - 1] = true;
- }
- for(int j = idx_of_same_val[arr[t]].size() - 1; j >= 0 ; j--){
- if(idx_of_same_val[arr[t]][j] != t && !visited[idx_of_same_val[arr[t]][j]]){
- q.push(idx_of_same_val[arr[t]][j]);
- visited[idx_of_same_val[arr[t]][j]] = true;
- }
- }
- }
- steps += 1;
- }
- return steps;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement