Problem

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]
]

Return4

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

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

Return4

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

思路

  1. Do DFS from every cell
  2. Compare every 4 direction and skip cells that are out of boundary or smaller
  3. Get matrix max from every cell's max
  4. Use matrix[x][y] <= matrix[i][j] so we don't need a visited[m][n] array
  5. The key is to cache the distance because it's highly possible to revisit a cell

  6.   public int longestIncreasingPath(int[][] matrix) {
          if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
    
          int m = matrix.length, n = matrix[0].length;
          int[][] cache = new int[m][n];
          int res = 0;
          for (int i = 0; i < matrix.length; i++) {
              for (int j = 0; j < matrix[i].length; j++) {
                  res = Math.max(res, dfs(matrix, i, j, cache));
              }
          }
    
          return res;
    
      }
    
      int[] dx = {1, -1, 0, 0};
      int[] dy = {0, 0, 1, -1};
    
      private int dfs (int[][] matrix, int x, int y, int[][] cache) {
          if (cache[x][y] != 0) return cache[x][y];
    
          int m = matrix.length;
          int n = matrix[0].length;
    
          int res = 1;
    
          for (int i = 0; i < 4; i++) {
              int x2 = x + dx[i];
              int y2 = y + dy[i];
    
              if (x2 >= m || x2 < 0 || y2 >= n || y2 < 0 || matrix[x2][y2] <= matrix[x][y]) continue;
    
              res = Math.max(dfs(matrix, x2, y2, cache) + 1, res);
          }
    
          cache[x][y] = res;
    
          return res;
      }
    

results matching ""

    No results matching ""