标签:
1 public class Solution { 2 private int[][] matrix; 3 private Map<Integer, Integer> visited; 4 public int longestIncreasingPath(int[][] matrix) { 5 if (matrix.length == 0 || matrix[0].length == 0) { 6 return 0; 7 } 8 this.matrix = matrix; 9 this.visited = new HashMap<>(); 10 int result = 1; 11 for (int i = 0; i < matrix.length; i++) { 12 for (int j = 0; j < matrix[0].length; j++) { 13 result = Math.max(findPath(i, j, Integer.MIN_VALUE), result); 14 } 15 } 16 return result; 17 } 18 19 private int findPath(int x, int y, int prev) { 20 if (x < 0 || x >= matrix.length || y < 0 || y >= matrix[0].length || prev >= matrix[x][y]) { 21 return 0; 22 } 23 24 if (visited.containsKey(x * matrix[0].length + y)) { 25 return visited.get(x * matrix[0].length + y); 26 } 27 28 int maxLength = 0; 29 maxLength = Math.max(findPath(x + 1, y, matrix[x][y]) + 1, maxLength); 30 maxLength = Math.max(findPath(x - 1, y, matrix[x][y]) + 1, maxLength); 31 maxLength = Math.max(findPath(x, y + 1, matrix[x][y]) + 1, maxLength); 32 maxLength = Math.max(findPath(x, y - 1, matrix[x][y]) + 1, maxLength); 33 visited.put(x*matrix[0].length + y, maxLength); 34 return maxLength; 35 } 36 }
1. Do not mess it up with number of islands. Each path extends only choose one.
Longest increasing Path in a Matrix
标签:
原文地址:http://www.cnblogs.com/shuashuashua/p/5634700.html