码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] Longest Increasing Continuous subsequence II

时间:2015-05-26 17:54:40      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

http://www.lintcode.com/en/problem/longest-increasing-continuous-subsequence-ii/#

Give you an integer matrix (with row size n, column size m),find the longest increasing continuous subsequence in this matrix. (The definition of the longest increasing continuous subsequence here can start at any row or column and go up/down/right/left any direction).

Example

Given a matrix:

[
  [1 ,2 ,3 ,4 ,5],
  [16,17,24,23,6],
  [15,18,25,22,7],
  [14,19,20,21,8],
  [13,12,11,10,9]
]
这道题使用dfs+dp,在dfs时更新状态,状态转移方程为 dp[(i,j)] = max(dp[(smaller neibors of all)])  + 1,来看代码:
class Solution {
public:
    /**
     * @param A an integer matrix
     * @return an integer
     */
    int longestIncreasingContinuousSubsequenceII(vector<vector<int>>& A) {
        if (A.empty() || A[0].empty()) {
            return 0;
        } 
        
        int ret = 0;
        int maxRow = A.size();
        int maxCol = A[0].size();
        vector<vector<int>> dp(maxRow, vector<int>(maxCol));
        for (int i = 0; i < maxRow; i++) {
            for (int j = 0; j < maxCol; j++) {
                ret = max(ret, dfs(i, j, maxRow, maxCol, A, dp));
            }
        }
        
        return ret;
    }
    
private:
    int dfs(int i, int j, int maxRow, int maxCol,
             const vector<vector<int>> &A,
             vector<vector<int>> &dp) {
        // 记忆化搜索,如果有值(之前dfs已经计算出的)直接返回,不再计算 
        if (dp[i][j] != 0) {
            return dp[i][j];
        }
        
        // 从up开始顺时针
        const int dx[] = {0, 1, 0, -1};
        const int dy[] = {-1, 0, 1, 0};
        
        // dfs更新dp状态
        for (int ix = 0; ix < 4; ix++) {
            int x = i + dx[ix];
            int y = j + dy[ix];
            if (0 <= x && x < maxRow && 0 <= y && y < maxCol && A[i][j] < A[x][y]) {
                dp[i][j] = max(dp[i][j], dfs(x, y, maxRow, maxCol, A, dp));
            } 
        }
        
        return ++dp[i][j];
    }
};

[LintCode] Longest Increasing Continuous subsequence II

标签:

原文地址:http://www.cnblogs.com/jianxinzhou/p/4530825.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!