leetcode329. 矩阵中的最长递增路径(dfs)
生活随笔
收集整理的這篇文章主要介紹了
leetcode329. 矩阵中的最长递增路径(dfs)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個整數矩陣,找出最長遞增路徑的長度。對于每個單元格,你可以往上,下,左,右四個方向移動。 你不能在對角線方向上移動或移動到邊界外(即不允許環繞)。示例 1:輸入: nums =
[[9,9,4],[6,6,8],[2,1,1]
]
輸出: 4
解釋: 最長遞增路徑為 [1, 2, 6, 9]。
代碼
class Solution {int[][] check;public int longestIncreasingPath(int[][] matrix) {int[][] dir = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};if(matrix.length==0) return 0;int n=matrix.length,m=matrix[0].length;check=new int[n][m];//記錄下節點的最長遞增路徑int res=0;for(int i=0;i<n;i++)for(int j=0;j<m;j++){if(check[i][j]==0)//當前沒有計算路徑長度IncreasingPath(matrix,i,j,dir);res= Math.max(res,check[i][j]);//比較得出最大值}return res;}public int IncreasingPath(int[][] matrix,int x,int y,int[][] dir) {if(check[x][y]!=0) return check[x][y];int temp=0;check[x][y]=1;//以當前節點為起點for(int[] d:dir)//遍歷4個方向{int nextX=d[0]+x,nextY=d[1]+y;if(nextX<0||nextY<0||nextX>=matrix.length||nextY>=matrix[0].length||matrix[nextX][nextY]<=matrix[x][y]) continue;//不滿足的節點不訪問temp= Math.max(temp,IncreasingPath(matrix,nextX,nextY,dir));//找出最長路徑}check[x][y]+=temp;return check[x][y];} }總結
以上是生活随笔為你收集整理的leetcode329. 矩阵中的最长递增路径(dfs)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 女人梦到去世的老人好不好
- 下一篇: 做梦梦到原来的老板什么预兆