nikunjsoni

1368-2

Apr 27th, 2021
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int minCost(vector<vector<int>>& grid) {
  4.         int dirs[5][2] = {{0,0}, {0,1}, {0,-1}, {1,0}, {-1,0}};
  5.         const int INF = INT_MAX;
  6.         int rows = grid.size(), cols = grid[0].size();
  7.         int cost[rows][cols];
  8.        
  9.         for(int i=0; i<rows; i++)
  10.             for(int j=0; j<cols; j++)
  11.                 cost[i][j] = INF;
  12.                
  13.         deque<pair<int, int>> q;
  14.         q.push_back({0, 0});
  15.         cost[0][0] = 0;
  16.        
  17.         while(!q.empty()){
  18.             auto p = q.front();
  19.             q.pop_front();
  20.             int curX = p.first, curY = p.second;
  21.             int curDist = cost[curX][curY];
  22.             for(int dir=1; dir<=4; dir++){
  23.                 int nextX = curX+dirs[dir][0], nextY = curY+dirs[dir][1];
  24.                 if(nextX >= 0 && nextX < rows && nextY >=0 && nextY < cols){
  25.                     int weight = (dir == grid[curX][curY]) ? 0 : 1;
  26.                     if(curDist+weight < cost[nextX][nextY]){
  27.                         cost[nextX][nextY] = curDist+weight;
  28.                         if(weight)
  29.                             q.push_back({nextX, nextY});
  30.                         else
  31.                             q.push_front({nextX, nextY});
  32.                     }
  33.                 }
  34.             }
  35.         }
  36.         return cost[rows-1][cols-1];
  37.     }
  38. };
Advertisement
Add Comment
Please, Sign In to add comment