knakul853

Untitled

Jun 27th, 2020
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. /**
  2. knakul853
  3. **/
  4. class Solution {
  5. public:
  6.     int dx[4] = {0, 0, -1, 1};
  7.      int dy[4] = {1, -1, 0, 0};
  8.     int longestIncreasingPath(vector<vector<int>>& matrix) {
  9.        
  10.         if( matrix.empty() || matrix[0].empty()) return 0;
  11.        
  12.         int n = (int)matrix.size();
  13.         int m = (int)matrix[0].size();
  14.        
  15.         vector<vector<int>>dp(n, vector<int>(m, -1));
  16.        
  17.         int ans = 1;
  18.         for(int i=0;i<n;i++)
  19.         {
  20.             for(int j=0;j<m;j++)
  21.             {
  22.                 ans = max(ans, dfs(i, j, dp, matrix));
  23.             }
  24.         }
  25.        
  26.         return ans;
  27.     }
  28.    
  29.     int dfs(int i, int j, vector<vector<int>>&dp, vector<vector<int>>& matrix)
  30.     {
  31.        int& ret = dp[i][j];
  32.        
  33.         if( ret != -1) return ret;
  34.        
  35.         ret = 0;
  36.        
  37.         for(int dir=0; dir<4; dir++ )
  38.         {
  39.             int nx = i + dx[dir];
  40.             int ny = j + dy[dir];
  41.            
  42.             if( nx < 0 || ny < 0 || nx >= (int)dp.size() || ny >= (int)dp[0].size())continue;
  43.             if(matrix[nx][ny] <= matrix[i][j]) continue;
  44.            
  45.               ret = max(ret, dfs(nx, ny, dp, matrix));
  46.            
  47.         }
  48.         ret++;
  49.    
  50.         return ret;
  51.        
  52.        
  53.     }
  54. };
Add Comment
Please, Sign In to add comment