nikunjsoni

329

May 31st, 2021
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int longestIncreasingPath(vector<vector<int>>& grid) {
  4.         int m = grid.size(), n=grid[0].size();
  5.         int inDegree[m+1][n+1];
  6.         memset(inDegree, 0, sizeof inDegree);
  7.        
  8.         // Set inDegree of each vertex.
  9.         int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
  10.         for(int i=0; i<m; i++)
  11.             for(int j=0; j<n; j++)
  12.                 for(int k=0; k<4; k++){
  13.                     int nextX=i+dir[k][0], nextY=j+dir[k][1];
  14.                     if(nextX>=0 && nextX<m && nextY>=0 && nextY<n && grid[i][j]<grid[nextX][nextY])
  15.                         inDegree[nextX][nextY]++;
  16.                 }
  17.        
  18.         // Topo sort using BFS.
  19.         int level = 0;
  20.         queue<pair<int,int>> q;
  21.         for(int i=0; i<m; i++)
  22.             for(int j=0; j<n; j++)
  23.                 if(!inDegree[i][j])
  24.                     q.push({i,j});
  25.        
  26.         while(!q.empty()){
  27.             level++;
  28.             int sz = q.size();
  29.             for(int i=0; i<sz; i++){
  30.                 auto p = q.front(); q.pop();
  31.                 int curX=p.first, curY=p.second;
  32.                 for(int j=0; j<4; j++){
  33.                     int nextX=curX+dir[j][0], nextY=curY+dir[j][1];
  34.                     if(nextX>=0 && nextX<m && nextY>=0 && nextY<n && grid[nextX][nextY]>grid[curX][curY]){
  35.                         if(--inDegree[nextX][nextY] == 0)
  36.                             q.push({nextX,nextY});
  37.                     }
  38.                 }
  39.             }
  40.         }
  41.         return level;
  42.     }
  43. };
Advertisement
Add Comment
Please, Sign In to add comment