题目地址:
https://www.lintcode.com/problem/longest-increasing-path-in-a-matrix/description
给定一个 m m m行 n n n列的二维矩阵 A A A,求最长严格上升路径的长度。路径的每一步允许上下左右走一步。
可以记忆化搜索。设 f [ i ] [ j ] f[i][j] f[i][j]是以 A [ i ] [ j ] A[i][j] A[i][j]为起点的最长严格上升路径的长度,则有 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]}如果其四周都不大于 A [ i ] [ j ] A[i][j] A[i][j]则 f [ i ] [ j ] = 1 f[i][j]=1 f[i][j]=1。为了加速可以用记忆化。代码如下:
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;
}
}
时空复杂度 O ( m n ) O(mn) O(mn)。