[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
原创粉丝点击