矩阵中最长连续递增子序列

来源:互联网 发布:ssl 端口 编辑:程序博客网 时间:2024/06/05 14:19

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.

int x_1[4] = { 1, -1, 0, 0 };int y_1[4] = { 0, 0, -1, 1 };int dfs(vector<vector<int>>& matrix,int rows,int cols,int row, int col, vector<vector<int>>&dp){if (dp[row][col])return dp[row][col];int maxDepth = 1;for (int i = 0; i < 4; ++i){int x = row + x_1[i];int y = col + y_1[i];if (x < 0 || y < 0 || x >= rows|| y >= cols || matrix[x][y] <= matrix[row][col])continue;int len = dfs(matrix, rows, cols, x, y, dp) + 1;if (maxDepth < len)maxDepth = len;}dp[row][col] = maxDepth;return maxDepth;}int longestIncreasingPath(vector<vector<int>>& matrix) {if (matrix.empty())return 0;int rows = matrix.size();int cols = matrix[0].size();vector<vector<int>> dp(rows, vector<int>(cols, 0));int maxDepth = 1;for (int i = 0; i < rows; ++i){for (int j = 0; j < cols; ++j){int tmp = dfs(matrix,rows,cols, i, j, dp);if (maxDepth < tmp)maxDepth = tmp;}}return maxDepth;}


0 0
原创粉丝点击