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:
Input: nums = 
[
  [9,9,4],
  [6,6,8],
  [2,1,1]
] 
Output: 4 
Explanation: The longest increasing path is [1, 2, 6, 9].
Example 2:
Input: nums = 
[
  [3,4,5],
  [3,2,6],
  [2,2,1]
] 
Output: 4 
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.


class Solution {
    private static final int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
    public int longestIncreasingPath(int[][] matrix) {
      if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
     
      int[][] record = new int[matrix.length][matrix[0].length];
      int res = 1;
      for(int i = 0; i < matrix.length; i++){
        for(int j = 0; j < matrix[0].length; j++){
          int len = dfs(matrix, i, j, record);
          res = Math.max(res, len);
        }
      }
      return res;
    }
    private int dfs(int[][] matrix, int i, int j, int[][] record){
      int length = 1;
      
      // base case 
      if(record[i][j] != 0) return record[i][j];
      
      // else do regular dfs on 4 dirs and see if the nei is out of boundary and check ifs its increasing 
      for(int[] dir : dirs){
        int row = i + dir[0];
        int col = j + dir[1];
        
        // check boundary 
        if(row < 0 || col < 0 || row >= matrix.length || col >= matrix[0].length || matrix[i][j] >= matrix[row][col]) continue;
        
        // else, it's nei is bigger than the current num at matrix[i][j]
        int thisDir = dfs(matrix, row, col, record);
        length = Math.max(length, 1 + thisDir);
      }
      record[i][j] = length;
      return length;
    }
}
  

 

posted on 2018-09-20 18:15  猪猪&#128055;  阅读(101)  评论(0)    收藏  举报

导航