329. Longest Increasing Path in a Matrix

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).

Example 1:

nums = [
  [9,9,4],
  [6,6,8],
  [2,1,1]
]

Return 4
The longest increasing path is [1, 2, 6, 9].

Example 2:

nums = [
  [3,4,5],
  [3,2,6],
  [2,2,1]
]

Return 4
The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

題意:

在一個矩陣當中,找到最長遞增子序列的長度,路徑是可以上下左右移動的,但不能斜著移動。

題解:

利用加上備忘錄(memo)的DFS來解題

  1. 拜訪每一個格子當作起點
  2. 把該格子作為起點進行走訪,有下面兩種情況:
    1. 若該點的memo大於0,表示該格子已經被走訪過,返回該格子的memo紀錄
    2. 走訪該點的上下左右相鄰格子,並將從該起點的最大遞增子序列的長度紀錄至memo中,memo是紀錄矩陣中從此格子出發的最大子序列長度
    3. 比較走訪上下左右各個路徑的長度,紀錄最大值
    4. 若從此點出發的最長長度為0,要把它改為1(因為每個路徑最小的最大長度為1)
  3. 完成對所有起點的走訪後,再將最大值記錄下來
  4. 返回最大值
package LeetCode.Hard;

public class LongestIncreasingPathInAMatrix {
    public int longestIncreasingPath(int[][] matrix) {
        if (matrix == null || matrix.length == 0) {
            return 0;
        }
        
        int n = matrix.length;
        int m = matrix[0].length;
        
        int max = 1;
        int [][] memo = new int[n][m];
        for(int i = 0; i < n; i ++) {
            for(int j = 0; j < m; j ++) {
                max = Math.max(helper(i, j, matrix, memo), max);
            }
        }
        
        return max;
    }
    
    int helper(int i, int j, int[][] matrix, int[][] memo) {
        if(memo[i][j] > 0) //走過了(因為該格已經有答案,可以直接套用,也在走到起點這一格時,直接使用起點這一格的答案)
            return memo[i][j];
        
        //走訪方向
        int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        
        //依序對4個方向進行走訪
        for(int[] dir : dirs) {
            int x = i + dir[0];
            int y = j + dir[1];
            
            if(x < 0 || x >= matrix.length || y < 0 || y >= matrix[0].length)
                continue;
            if(matrix[x][y] <= matrix[i][j])
                continue;
            
            memo[i][j] = Math.max(memo[i][j], helper(x, y, matrix, memo) + 1);
        }
        
        //每一格都至少為1
        memo[i][j] = Math.max(memo[i][j], 1);
        
        return memo[i][j];
    }
}

猜你喜欢

转载自blog.csdn.net/aspspspsp/article/details/76922750