329题-矩阵中的最长递增路径

1.1题目

给定一个整数矩阵,找出最长递增路径的长度。对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。
示例1:

示例2:

1.2解答

很显然只能将所有情况完全遍历一次,将以任意一点为起点的情况全部遍历完,也就是对每个点进行深度优先搜索。但是这样的时间复杂度直接爆炸。所以我们需要考虑如何优化。很显然我们这里有很多的重复情况,我们就建立一张缓存表来放置以前计算出来的值。

1.3代码

package solution;

/**
 * @author xgj
 */
public class Solution {
    private final int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    private int rows, columns;

    public int longestIncreasingPath(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return 0;
        }
        this.rows = matrix.length;
        this.columns = matrix[0].length;
        int[][] memo = new int[this.rows][this.columns];
        int ans = 0;
        for (int i = 0; i < this.rows; ++i) {
            for (int j = 0; j < this.columns; ++j) {
                ans = Math.max(ans, dfs(matrix, i, j, memo));
            }
        }
        return ans;
    }

    public int dfs(int[][] matrix, int row, int column, int[][] memo) {
        if (memo[row][column] != 0) {
            return memo[row][column];
        }
        //该位置以自己为起点,以自己为终点可以构成一个长度为一的数组。
        ++memo[row][column];
        for (int[] dir : dirs) {
            int newRow = row + dir[0], newColumn = column + dir[1];
            if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns && matrix[newRow][newColumn] > matrix[row][column]) {
                memo[row][column] = Math.max(memo[row][column], dfs(matrix, newRow, newColumn, memo) + 1);
            }
        }
        return memo[row][column];
    }
}


猜你喜欢

转载自www.cnblogs.com/jiezao/p/13379458.html