Subject address:
https://www.lintcode.com/problem/longest-increasing-path-in-a-matrix/description
Given a mmm linennTwo-dimensional matrixAA with n columnsA , find the length of the longest strict ascent path. Each step of the path allows one step up, down, left and right.
Can memorize search. Let f [i] [j] f[i][j]F [ I ] [ J ] Ze以A [i] [j] AA [ i ] [ j ] is the length of the longest strictly ascending path from the starting point, then f [i] [j] = 1 + max A [i + Δ i] [j + Δ j]> A [i] [j] {f [i + Δ i] [j + Δ j]} f[i][j]=1+\max_{A[i+\Delta i][j+\Delta j]>A[i][ j]}\{f[i+\Delta i][j+\Delta j]\}f[i][j]=1+A[i+Δi][j+Δj]>A[i][j]max{ f[i+Δi][j+Δ j ] } if it is not larger thanA [i] [j] A[i][j]A[i][j]则 f [ i ] [ j ] = 1 f[i][j]=1 f[i][j]=1 . Memorization can be used to speed up. code show as below:
public class Solution {
/**
* @param matrix: A matrix
* @return: An integer.
*/
public int longestIncreasingPath(int[][] matrix) {
// Write your code here.
int res = 0, m = matrix.length, n = matrix[0].length;
int[][] dp = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
res = Math.max(res, dfs(i, j, matrix, dp));
}
}
return res;
}
private int dfs(int x, int y, int[][] mat, int[][] dp) {
// 有记忆则调取记忆
if (dp[x][y] != 0) {
return dp[x][y];
}
int[] d = {
1, 0, -1, 0, 1};
int res = 1;
for (int i = 0; i < 4; i++) {
int nextX = x + d[i], nextY = y + d[i + 1];
if (inBound(nextX, nextY, mat) && mat[nextX][nextY] > mat[x][y]) {
res = Math.max(res, 1 + dfs(nextX, nextY, mat, dp));
}
}
// 存储记忆
dp[x][y] = res;
return res;
}
private boolean inBound(int x, int y, int[][] mat) {
return 0 <= x && x < mat.length && 0 <= y && y < mat[0].length;
}
}
Time and space complexity O (mn) O(mn)O ( m n )。