1. 程式人生 > >LeetCode 329. 矩陣中的最長遞增路徑

LeetCode 329. 矩陣中的最長遞增路徑

給定一個整數矩陣,找出最長遞增路徑的長度。

對於每個單元格,你可以往上,下,左,右四個方向移動。 你不能在對角線方向上移動或移動到邊界外(即不允許環繞)。

示例 1:

輸入: nums = 
[
  [9,9,4],
  [6,6,8],
  [2,1,1]
] 
輸出: 4 
解釋: 最長遞增路徑為 [1, 2, 6, 9]。

示例 2:

輸入: nums = 
[
  [3,4,5],
  [3,2,6],
  [2,2,1]
] 
輸出: 4 
解釋: 最長遞增路徑是 [3, 4, 5, 6]。注意不允許在對角線方向上移動。
//思路一
class Solution {   
    public static int n,m;
    
    public static int f[][] = new int[1000][1000];
    
    public static boolean check(int x,int y,int nx,int ny,int[][] mat){//能不能走到下一個格子,那些格子可以繼續拓展
        return x >=0 && y>= 0 && nx >=0 && ny >=0 && x < n && y <m && nx < n && ny <m && mat[x][y] > mat[nx][ny];
    }
    
    public int robot(int x,int y,int[][] mat){//最遠能走多少步
        
        if(f[x][y] > 0){
            return f[x][y];
        }
        
        int max = 0;
        for(int dx = -1;dx <= 1;dx++){
            for (int dy = -1;dy <= 1;dy++){
                if(Math.abs(dx + dy) ==1){
                    if(check(x,y,x+dx,y+dy,mat))
                        max = Math.max(max,robot(x+dx,y+dy,mat)) ;
                }
            }
        }
        f[x][y] = max + 1;
        return max+1;
    }    
    
    //列舉最後出發的位置
    public int longestIncreasingPath(int[][] matrix) { 

        n = matrix.length;
        if (n==0){
            return 0;
        }
        
        m = matrix[0].length;
        
        for(int i = 0;i< n;i++){
            for(int j = 0;j < m; j++){
                f[i][j] = 0;
            }
        }

        int ans = 0;
        for(int i =0;i<n;i++){
            for(int j = 0;j<m;j++){
                ans = Math.max(ans,robot(i,j,matrix));
            }
        }
        return ans;
    }
}

//思路二
public class Solution {
    private int[] ro = {-1, 1, 0, 0};
    private int[] co = {0, 0, -1, 1};
    private int find(int[][] matrix, boolean[][] visited, int[][] path, int row, int col) {
        
        if (visited[row][col]) 
            return path[row][col];
        
        path[row][col] = 1;
        for(int i=0; i<4; i++) {
            int r = row + ro[i];
            int c = col + co[i];
            if (r>=0 && r<matrix.length && c>=0 && c<matrix[r].length && matrix[row][col] > matrix[r][c]) {
                path[row][col] = Math.max(path[row][col], find(matrix, visited, path, r, c)+1);
            }
        }
        visited[row][col] = true;
        return path[row][col];
    }
    
    public int longestIncreasingPath(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) 
            return 0;
        
        boolean[][] visited = new boolean[matrix.length][matrix[0].length];
        
        int[][] path = new int[matrix.length][matrix[0].length];
        
        int max = 0;
        
        for(int i=0; i<matrix.length; i++) {
            for(int j=0; j<matrix[i].length; j++) {
                max = Math.max(max, find(matrix, visited, path, i, j));
            }
        }
        return max;
    }
}