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).

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]
]

return 25

A question on Lintcode, this question is very interesting, the requirement is two-dimensional matrix inside a continuous incremental sequence. It is continuous in the four directions can be matrix. As an example of the matrix is ​​in the outer ring around the circle. And the longest increasing subsequence similar. We state here defined as dp dp [i] [j] is the length of the longest continuous incremental sequence to i, j is the ending.

Recursion relation can be derived: dp [i] [j] = max {dp [i-1] [j] +1 (A [ii] [j] <A [i] [j]), dp [i ] [j-1] +1 (A [i] [j-1] <A [i] [j]), dp [i + 1] [j] +1 (A [i + 1] [j] < A [i] [j]), dp [i] [j + 1] +1 (A [i] [j + 1] <A [i] [j]) that is recursive in four directions .

Initialization dp [i] [j] = 1, i.e., the current character.

Final state max (dp [i] [j]). Since dp [i] [j] defines the length of the longest increasing subsequence certain end position. The matrix, a total of m * n elements, then these elements can been traversed. Complexity is O (n ^ 2), which is a problem because the length of the initialization, it is also possible here longest length is 1, the matrix using a dp visited matrix while it is difficult to play. Also we need to set up a flag matrix.

code show as below:

class Solution:
    # @param {int[][]} A an integer matrix
    # @return {int}  an integer
    def longestIncreasingContinuousSubsequenceII(self, A):
        if not A or not A[0]:
            return 0
        n = len(A)
        m = len(A[0])
        flag = [[False]*m for i in xrange(n)]
        dp = [[1]*m for i in xrange(n)]
        maxVal = 1
        for i in xrange(n):
            for j in xrange(m):
                maxVal = max(maxVal, self.search(A, flag, dp, i, j))
        return maxVal
    def search(self, A, flag, dp, x, y):
        if flag[x][y]:
            return dp[x][y]
        dx = [0, 0, -1, 1]
        dy = [1, -1, 0, 0]
        
        for i in xrange(4):
            if 0 <= x + dx[i] < len(A) and 0 <= y+dy[i] < len(A[0]) and A[x][y] > A[x+dx[i]][y+dy[i]]:
                dp[x][y] = max(dp[x][y], self.search(A, flag, dp, x+dx[i], y+dy[i])+1)
        flag[x][y] = True
        return dp[x][y]

 

 

Reproduced in: https: //www.cnblogs.com/sherylwang/p/5616824.html

Guess you like

Origin blog.csdn.net/weixin_34219944/article/details/94525981