|
| 1 | +#define vvi vector<vector<int>> |
| 2 | +class Solution { |
| 3 | +public: |
| 4 | + bool insideBounds(int i, int j, int rows, int cols){ |
| 5 | + return (i < rows && i >= 0) && (j < cols && j >= 0); |
| 6 | + } |
| 7 | + |
| 8 | + int DFS(vvi &matrix, int i, int j, int depth, vvi &DP, vvi &visit, int rows, int cols){ |
| 9 | + int maxDepth = depth; |
| 10 | + if(DP[i][j] != -1) return depth+DP[i][j]; |
| 11 | + visit[i][j] = 1; |
| 12 | + |
| 13 | + |
| 14 | + if(insideBounds(i+1, j, rows, cols) && visit[i+1][j] == 0 && matrix[i+1][j] > matrix[i][j]){ |
| 15 | + int d = (DP[i+1][j] == -1)? DFS(matrix, i+1, j, depth+1, DP, visit, rows, cols): depth+DP[i+1][j]; |
| 16 | + maxDepth = max(maxDepth, d); |
| 17 | + } |
| 18 | + if(insideBounds(i, j+1, rows, cols) && visit[i][j+1] == 0 && matrix[i][j+1] > matrix[i][j]){ |
| 19 | + int d = (DP[i][j+1] == -1)? DFS(matrix, i, j+1, depth+1, DP, visit, rows, cols): depth+DP[i][j+1]; |
| 20 | + maxDepth = max(maxDepth, d); |
| 21 | + } |
| 22 | + if(insideBounds(i-1, j, rows, cols) && visit[i-1][j] == 0 && matrix[i-1][j] > matrix[i][j]){ |
| 23 | + int d = (DP[i-1][j] == -1)? DFS(matrix, i-1, j, depth+1, DP, visit, rows, cols): depth+DP[i-1][j]; |
| 24 | + maxDepth = max(maxDepth, d); |
| 25 | + } |
| 26 | + if(insideBounds(i, j-1, rows, cols) && visit[i][j-1] == 0 && matrix[i][j-1] > matrix[i][j]){ |
| 27 | + int d = (DP[i][j-1] == -1)? DFS(matrix, i, j-1, depth+1, DP, visit, rows, cols): depth+DP[i][j-1]; |
| 28 | + maxDepth = max(maxDepth, d); |
| 29 | + } |
| 30 | + |
| 31 | + visit[i][j] = 0; |
| 32 | + DP[i][j] = max(maxDepth, depth) - depth + 1; |
| 33 | + return max(maxDepth, depth); |
| 34 | + } |
| 35 | + |
| 36 | + int longestIncreasingPath(vvi& matrix) { |
| 37 | + int rows = matrix.size(); |
| 38 | + if(rows == 0) return 0; |
| 39 | + int cols = matrix[0].size(); |
| 40 | + |
| 41 | + vvi DP (rows, vector<int> (cols, -1)); |
| 42 | + vvi visit (rows, vector<int> (cols, 0)); |
| 43 | + int maxLen = -1; |
| 44 | + for(int i = 0; i < rows; i++){ |
| 45 | + for(int j = 0; j < cols; j++){ |
| 46 | + if(DP[i][j] == -1){ |
| 47 | + DP[i][j] = DFS(matrix, i, j, 1, DP, visit, rows, cols); |
| 48 | + } |
| 49 | + |
| 50 | + if(DP[i][j] > maxLen) maxLen = DP[i][j]; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return maxLen; |
| 55 | + } |
| 56 | +}; |
0 commit comments