|
| 1 | +/* |
| 2 | +Longest Increasing Path in a Matrix |
| 3 | +=================================== |
| 4 | +
|
| 5 | +Given an m x n integers matrix, return the length of the longest increasing path in matrix. |
| 6 | +
|
| 7 | +From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed). |
| 8 | +
|
| 9 | +Example 1: |
| 10 | +Input: matrix = [[9,9,4],[6,6,8],[2,1,1]] |
| 11 | +Output: 4 |
| 12 | +Explanation: The longest increasing path is [1, 2, 6, 9]. |
| 13 | +
|
| 14 | +Example 2: |
| 15 | +Input: matrix = [[3,4,5],[3,2,6],[2,2,1]] |
| 16 | +Output: 4 |
| 17 | +Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed. |
| 18 | +
|
| 19 | +Example 3: |
| 20 | +Input: matrix = [[1]] |
| 21 | +Output: 1 |
| 22 | +
|
| 23 | +Constraints: |
| 24 | +m == matrix.length |
| 25 | +n == matrix[i].length |
| 26 | +1 <= m, n <= 200 |
| 27 | +0 <= matrix[i][j] <= 231 - 1 |
| 28 | +*/ |
| 29 | + |
| 30 | +class Solution |
| 31 | +{ |
| 32 | +public: |
| 33 | + int dirs[4][4] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; |
| 34 | + |
| 35 | + int dfs(vector<vector<int>> &mat, int r, int c, vector<vector<int>> &memo) |
| 36 | + { |
| 37 | + if (memo[r][c] != -1) |
| 38 | + return memo[r][c]; |
| 39 | + |
| 40 | + int n = mat.size(), m = mat[0].size(); |
| 41 | + int ans = 0; |
| 42 | + for (auto &dir : dirs) |
| 43 | + { |
| 44 | + int nextR = r + dir[0], nextC = c + dir[1]; |
| 45 | + if (nextR < 0 || nextC < 0 || nextR >= n || nextC >= m || mat[r][c] >= mat[nextR][nextC]) |
| 46 | + continue; |
| 47 | + ans = max(ans, dfs(mat, nextR, nextC, memo)); |
| 48 | + } |
| 49 | + |
| 50 | + memo[r][c] = ans + 1; |
| 51 | + return memo[r][c]; |
| 52 | + } |
| 53 | + |
| 54 | + int longestIncreasingPath(vector<vector<int>> &matrix) |
| 55 | + { |
| 56 | + int n = matrix.size(), m = matrix[0].size(); |
| 57 | + vector<vector<int>> memo(n + 1, vector<int>(m + 1, -1)); |
| 58 | + |
| 59 | + int ans = 0; |
| 60 | + for (int i = 0; i < n; ++i) |
| 61 | + { |
| 62 | + for (int j = 0; j < m; ++j) |
| 63 | + { |
| 64 | + int curr_ans = dfs(matrix, i, j, memo); |
| 65 | + ans = max(ans, curr_ans); |
| 66 | + } |
| 67 | + } |
| 68 | + return ans; |
| 69 | + } |
| 70 | +}; |
0 commit comments