码迷,mamicode.com
首页 > 其他好文 > 详细

Longest increasing Path in a Matrix

时间:2016-07-02 06:58:50      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

 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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!