329. Longest Increasing Path in a Matrix

这是一道经典的DFS问题,
这个solution里面我用了best array同时记录结果和做为visited.
这个是在退出的时候标记visited.因为是严格递增的,所以不需要避免环。
所以不需要visiting, 只需要一个visited.

class Solution {
    int[][] OFFSETS;
    public int longestIncreasingPath(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0 ) return 0;
        int[] ans = new int[1];
        OFFSETS = new int[][] {{-1, 0}, {1,0}, {0, -1}, {0, 1}};
        int N = matrix.length, M = matrix[0].length;
        int[][] best = new int[N][M]; //best served also as visited;
        for (int r = 0; r < N; r++) {
            for (int c = 0; c < M; c++) {
                if (best[r][c] == 0) {
                    dfs(matrix, r, c, best, ans, N, M);
                }
            }
        }
        return ans[0];
    }
    private int dfs(int[][] matrix, int r, int c, int[][] best, int[] ans, int N, int M) {
        if (best[r][c] != 0) return best[r][c];
        int cnt = 1;
        for (int[] os : OFFSETS) {
            int nr = r + os[0], nc = c + os[1];
            if (nr < 0 || nc < 0 || nr >= N || nc >= M ) continue;
            if (matrix[nr][nc] <= matrix[r][c]) continue;
            cnt = Math.max(cnt, 1 + dfs(matrix, nr, nc, best, ans, N, M));
        }
        best[r][c] = cnt; 
        ans[0] = Math.max(ans[0], cnt);
        return cnt;
    }
}

你可能感兴趣的:(329. Longest Increasing Path in a Matrix)