jayati

Jump Game IV

Mar 5th, 2023
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int minJumps(vector<int>& arr)
  4.     {
  5.         int n = arr.size();
  6.         unordered_map<int, vector<int>>mp;
  7.         for (int i = 0; i < n; i++) mp[arr[i]].push_back(i);
  8.        
  9.         queue<int>q;
  10.         vector<bool>visited(n, false);
  11.         q.push(0);
  12.         int steps = 0;
  13.         while(!q.empty())
  14.         {
  15.             int size = q.size();
  16.             while(size--)
  17.             {
  18.                 int currIdx = q.front();
  19.                 q.pop();
  20.                 if (currIdx == n - 1) return steps;
  21.  
  22.                 if (currIdx + 1 < n && !visited[currIdx + 1])
  23.                 {
  24.                     visited[currIdx + 1] = true;
  25.                     q.push(currIdx + 1);
  26.                 }
  27.                 if (currIdx - 1 >= 0 && !visited[currIdx - 1])
  28.                 {
  29.                     visited[currIdx - 1] = true;
  30.                     q.push(currIdx - 1);
  31.                 }
  32.                 for (int newIdx : mp[arr[currIdx]])
  33.                 {                                
  34.                     if (!visited[newIdx])
  35.                     {
  36.                         visited[newIdx] = true;
  37.                         q.push(newIdx);
  38.                     }
  39.                 }
  40.                 mp[arr[currIdx]].clear();    
  41.             }
  42.             steps++;
  43.         }
  44.         return -1;
  45.     }
  46. };
Advertisement
Add Comment
Please, Sign In to add comment