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

329. Longest Increasing Path in a Matrix

时间:2016-07-07 07:29:47      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

建立一个二维的表,每一个格子的值,都是以此位置为结尾的最长的增序序列。所以这个值需要上下左右四个值来确定,就是一个dfs。

需要注意的是,如果已经被算出结果的值不需要再算一遍。

 

所以整个dfs的结构是,算出上下左右的值,找到最大的那个,当前值是四周比它小的最长序列的长度+1,否则为1

 1     private static final int[][] directions = {{0,1},{0,-1},{-1,0},{1,0}};
 2     
 3     public int longestIncreasingPath(int[][] matrix) {
 4         if(matrix.length == 0 || matrix[0].length == 0) {
 5             return 0;
 6         }
 7         int row = matrix.length;
 8         int col = matrix[0].length;
 9         int[][] res = new int[row][col];
10         int max = 1;
11         for(int i = 0; i < row; i++) {
12             for(int j = 0; j < col; j++) {
13                 if (res[i][j] == 0) {
14                     max = Math.max(max, dfs(matrix, res, i, j));
15                 }
16             }
17         }
18         return max;
19     }
20     
21     private int dfs(int[][] matrix, int[][] res, int x, int y) {
22         if(res[x][y] != 0) {
23             return res[x][y];
24         }
25         int max = 1;
26         for (int[] direction : directions) {
27             int newX = x + direction[0];
28             int newY = y + direction[1];
29             if (newX < 0 || newX >= matrix.length || newY < 0 || newY >= matrix[0].length) {
30                 continue;
31             }
32             if (matrix[newX][newY] < matrix[x][y]) {
33                 max = Math.max(max, 1 + dfs(matrix, res, newX, newY));
34             }
35         }
36         res[x][y] = max;
37         return max;
38     }

 

329. Longest Increasing Path in a Matrix

标签:

原文地址:http://www.cnblogs.com/warmland/p/5648676.html

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