LeetCode 329 Longest Increasing Path in a Matrix (记忆化搜索)
来源:互联网 发布:godaddy域名被转走 编辑:程序博客网 时间:2024/05/22 13:36
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.
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
题目链接:https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
public class Solution { int [][]dp; int dx[] = {0, 0, 1, -1}; int dy[] = {1, -1, 0, 0}; int DFS (int x, int y, int n, int m, int[][] matrix) { if (dp[x][y] != 0) { return dp[x][y]; } dp[x][y] = 1; for (int i = 0; i < 4; i ++) { int xx = x + dx[i]; int yy = y + dy[i]; if (xx >= 0 && xx < n && yy >= 0 && yy < m && matrix[xx][yy] < matrix[x][y]) { dp[x][y] = Math.max(dp[x][y], DFS(xx, yy, n, m, matrix) + 1); } } return dp[x][y]; } public int longestIncreasingPath(int[][] matrix) { int n = matrix.length; if (n == 0) { return 0; } int m = matrix[0].length; dp = new int[n + 1][m + 1]; for (int i = 0; i < n; i ++) { Arrays.fill(dp[i], 0); } int ans = 1; for (int i = 0; i < n; i ++) { for (int j = 0; j < m; j ++) { ans = Math.max(ans, DFS(i, j, n, m, matrix)); } } return ans; }}
0 0
- LeetCode 329 Longest Increasing Path in a Matrix (记忆化搜索)
- Longest Increasing Path in a Matrix (DFS+记忆化搜索)
- leetcode_[python/C++] 329. Longest Increasing Path in a Matrix(DFS+记忆化搜索)
- Longest Increasing Path in a Matrix (第五周 记忆化搜索)
- leetcode Longest Increasing Path in a Matrix
- [LeetCode] Longest Increasing Path in a Matrix
- leetcode: Longest Increasing Path in a Matrix
- Leetcode: Longest Increasing Path in a Matrix
- leetcode:Longest Increasing Path in a Matrix
- [LeetCode]Longest Increasing Path in a Matrix
- [Leetcode]Longest Increasing Path in a Matrix
- Longest Increasing Path in a Matrix | leetcode
- LeetCode Longest Increasing Path in a Matrix
- 【Leetcode】Longest Increasing Path in a Matrix
- LeetCode:Longest Increasing Path in a Matrix
- [leetcode]Longest Increasing Path in a Matrix
- Leetcode Longest Increasing Path in a Matrix
- [LeetCode]Longest Increasing Path in a Matrix
- 在CI框架中如何实现伪静态
- ListView使用复用缓存
- [JZOJ4798] 天使的分裂
- spring框架中的bean对象的声明周期
- iOS获取UUID,并使用keychain存储
- LeetCode 329 Longest Increasing Path in a Matrix (记忆化搜索)
- 【poj3070】 Fibonacci
- 第4周项目2 长方形面积
- Ubuntu16.04 apache2配置虚拟主机
- PHP的serialize序列化数据与JSON格式化数据
- 使用RecycleView和SearchView总结(一)
- WebRTC工具`gn`简介
- 教你认清HttpURLConnection里面的CookieManager,CookieStore,CookieHandler,HttpCookie,CookiePolicy
- SparkSql寻医问药问答分析第二次分析