[Leetcode] #329 Longest Increasing Path in a Matrix (DFS)
来源:互联网 发布:汉朝为什么灭亡 知乎 编辑:程序博客网 时间:2024/06/06 02:12
Discription:
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.
Solution:
int rows, cols;vector<vector<int>> dirs = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };int dfs(vector<vector<int>>& matrix, int x, int y, vector<vector<int>> &path){if (path[x][y] != 0) return path[x][y];int maxLen = 1;for (int i = 0; i < dirs.size(); i++){int x1 = x + dirs[i][0], y1 = y + dirs[i][1];if (x1 >= 0 && x1 < rows && y1 >= 0 && y1<cols && matrix[x1][y1]>matrix[x][y]){int len = 1 + dfs(matrix, x1, y1, path);maxLen = max(len, maxLen);}}path[x][y] = maxLen;return maxLen;}int longestIncreasingPath(vector<vector<int>>& matrix) {if (matrix.empty()) return 0;rows = matrix.size();cols = matrix[0].size();vector<vector<int>> path(rows, vector<int>(cols, 0));int result = 1;for (int i = 0; i < rows; i++){for (int j = 0; j < cols; j++){int len = dfs(matrix, i, j, path);result = max(len, result);}}return result;}
0 0
- leetcode 329 : Longest Increasing Path in a Matrix : dfs+dp
- [Leetcode] #329 Longest Increasing Path in a Matrix (DFS)
- 329.LeetCode Longest Increasing Path in a Matrix(hard)[DFS]
- 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
- 【LEETCODE】329-Longest Increasing Path in a Matrix [Python]
- RTMP流媒体播放流程解析
- 年薪10万的人,都是怎么努力的?
- el 字符串empty 和 eq null比较
- github提示Permission denied (publickey)
- Linux常用命令之系统管理命令top free df du
- [Leetcode] #329 Longest Increasing Path in a Matrix (DFS)
- miniui表格下拉树combobox使用方法与全选或选某一个
- c(数据结构)下树的创建的非递归算法
- 打开IE浏览器出现 SPI can’t create GMem lock
- LMS最小均方算法
- 常见获取验证码倒计时60s
- 高效能程序员的七个习惯
- Linux 命令学习
- Java实现切图功能