Advertisement
nikunjsoni

778-1

Apr 28th, 2021
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1. class Solution {
  2.  
  3. struct node{
  4.     int x, y, t;
  5.     node(int x, int y, int t): x(x), y(y), t(t){}
  6.     bool operator<(const node &tmp) const{
  7.         return t > tmp.t;
  8.     }
  9. };
  10.    
  11. public:
  12.     int swimInWater(vector<vector<int>>& grid) {
  13.         int ans = 0, rows = grid.size(), cols = grid[0].size();
  14.         int d[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
  15.         bool vis[rows][cols];
  16.         memset(vis, 0, sizeof vis);
  17.        
  18.         priority_queue<node> q;
  19.         q.push(node(0, 0, grid[0][0]));
  20.         vis[0][0] = true;
  21.        
  22.         while(!q.empty()){
  23.             node curr = q.top();
  24.             q.pop();
  25.             ans = max(ans, curr.t);
  26.             if(curr.x == rows-1 && curr.y == cols-1)
  27.                 return ans;
  28.             for(int i=0; i<4; i++){
  29.                 int nextX = curr.x+d[i][0], nextY = curr.y+d[i][1];
  30.                 if(nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols || vis[nextX][nextY])
  31.                     continue;
  32.                 node next = node(nextX, nextY, grid[nextX][nextY]);
  33.                 q.push(next);
  34.                 vis[nextX][nextY] = true;
  35.             }
  36.         }
  37.         return ans;
  38.     }
  39. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement