329. Longest Increasing Path in a Matrix
来源:互联网 发布:怎样手机域名保护 编辑:程序博客网 时间:2024/05/22 15:04
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]]
Return 4
The longest increasing path is [1, 2, 6, 9]
.
Example 2:
nums = [ [3,4,5], [3,2,6], [2,2,1]]
Return 4
The longest increasing path is [3, 4, 5, 6]
. Moving diagonally is not allowed.
題意:
在一個矩陣當中,找到最長遞增子序列的長度,路徑是可以上下左右移動的,但不能斜著移動。
題解:
利用加上備忘錄(memo)的DFS來解題
- 拜訪每一個格子當作起點
- 把該格子作為起點進行走訪,有下面兩種情況:
- 若該點的memo大於0,表示該格子已經被走訪過,返回該格子的memo紀錄
- 走訪該點的上下左右相鄰格子,並將從該起點的最大遞增子序列的長度紀錄至memo中,memo是紀錄矩陣中從此格子出發的最大子序列長度
- 比較走訪上下左右各個路徑的長度,紀錄最大值
- 若從此點出發的最長長度為0,要把它改為1(因為每個路徑最小的最大長度為1)
- 完成對所有起點的走訪後,再將最大值記錄下來
- 返回最大值
package LeetCode.Hard;public class LongestIncreasingPathInAMatrix { public int longestIncreasingPath(int[][] matrix) { if (matrix == null || matrix.length == 0) { return 0; } int n = matrix.length; int m = matrix[0].length; int max = 1; int [][] memo = new int[n][m]; for(int i = 0; i < n; i ++) { for(int j = 0; j < m; j ++) { max = Math.max(helper(i, j, matrix, memo), max); } } return max; } int helper(int i, int j, int[][] matrix, int[][] memo) { if(memo[i][j] > 0) //走過了(因為該格已經有答案,可以直接套用,也在走到起點這一格時,直接使用起點這一格的答案) return memo[i][j]; //走訪方向 int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; //依序對4個方向進行走訪 for(int[] dir : dirs) { int x = i + dir[0]; int y = j + dir[1]; if(x < 0 || x >= matrix.length || y < 0 || y >= matrix[0].length) continue; if(matrix[x][y] <= matrix[i][j]) continue; memo[i][j] = Math.max(memo[i][j], helper(x, y, matrix, memo) + 1); } //每一格都至少為1 memo[i][j] = Math.max(memo[i][j], 1); return memo[i][j]; }}
阅读全文
1 0
- 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- 329. Longest Increasing Path in a Matrix
- leetcode Longest Increasing Path in a Matrix
- Webix入门()
- Struts2 入门 hellow word
- java面向对象的三个特征以及匿名内部类
- 注意:父类构造函数与子类构造函数的调用
- Unity Kinect体感开发注意点
- 329. Longest Increasing Path in a Matrix
- std里find和find_if
- Android中的setOffscreenPageLimit()
- 十道海量数据处理面试题与十个方法大总结
- Graphic使UI渐变
- JavaScript 高级教程
- CoreGraphics框架
- Handler线程切换实现原理
- 获取微信thumb_media_id