nikunjsoni

1368-1

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