[LeetCode] Longest Increasing Path in a Matrix

329. Longest Increasing Path in a Matrix

Given an m x n integers matrix, return the length of the longest increasing path in matrix.

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).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
int dp[200][200];
int dx[4]{0,1,0,-1}, dy[4]{-1,0,1,0};
int dfs(vector<vector<int>>& matrix, int& n, int& m, int y, int x) {
if(dp[y][x] != -1) return dp[y][x];
dp[y][x] = 1;
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0<=nx and nx < m and 0 <= ny and ny < n and matrix[ny][nx] > matrix[y][x]) {
dp[y][x] = max(dp[y][x], dfs(matrix,n,m,ny,nx) + 1);
}
}
return dp[y][x];
}
public:
int longestIncreasingPath(vector<vector<int>>& matrix) {
memset(dp,-1,sizeof(dp));
int n = matrix.size(), m = matrix[0].size(), res = 0;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
res = max(res, dfs(matrix, n, m, i, j));

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/08/PS/LeetCode/longest-increasing-path-in-a-matrix/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.