Leetcode 329. Longest Increasing Path in a Matrix

weixin_34208283發表於2018-03-12

Given an integer matrix, find the length of the longest increasing path.

From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).

思路:

  1. 對陣列中每個元素A,都嘗試尋找以A為起點的最長路徑。
  2. 用一個最大值路徑變數記錄當前尋找到的最長路徑。
  3. 由於嘗試遍歷每個元素,陣列中某些位置會被重複查詢,此時可以通過雜湊表來記錄以當前位置為起點的最長路徑,如果已經查詢過,則直接返回值。如果沒有被查詢過,在算出最大路徑值以後存放到雜湊表中,下次就不用再計算了。
public class LIPInMatrix329 {

    private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    private int m, n;

    public int longestIncreasingPath(int[][] matrix) {
        if (matrix.length == 0) {
            return 0;
        }
        m = matrix.length; n = matrix[0].length;
        int[][] cache = new int[m][n];
        int ans = 0;
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                ans = Math.max(ans, dfs(matrix, i, j, cache));
            }
        }
            
        return ans;
    }

    private int dfs(int[][] matrix, int x, int y, int[][] cache) {
        if (cache[x][y] != 0) {
            return cache[x][y];
        }
        
        cache[x][y] = 1;
        for (int[] d : dirs) {
            int tx = x + d[0], ty = y + d[1];
            if (0 <= tx && tx < m && 0 <= ty && ty < n && matrix[tx][ty] > matrix[x][y]) {
                cache[x][y] = Math.max(cache[x][y], 1 + dfs(matrix, tx, ty, cache));
            }
        }
        return cache[x][y];
    }
}

相關文章