给定一个整数矩阵(其中,有 n 行, m 列),请找出矩阵中的最长上升连续子序列。(最长上升连续子序列可从任意行或任意列开始,向上/下/左/右任意方向移动)。
1 class Solution: 2 """ 3 @param matrix: A 2D-array of integers 4 @return: an integer 5 """ 6 def longestContinuousIncreasingSubsequence2(self, matrix): 7 # write your code here 8 if matrix is None or len(matrix) == 0 or len(matrix[0]) == 0: 9 return 010 ans = [[0 for j in range(len(matrix[0]))] for i in range(len(matrix))]11 self.DIR = [(1, 0), (-1, 0), (0 ,1), (0, -1)]12 13 longest = 014 for i in range(len(matrix)):15 for j in range(len(matrix[0])):16 longest = max(longest, self.dfs(matrix, i, j, ans))17 return longest18 19 20 def dfs(self, matrix, i, j, ans):21 if ans[i][j] > 0:22 return ans[i][j]23 ans[i][j] = 124 for (di, dj) in self.DIR:25 next_i, next_j = i + di, j + dj26 if next_i not in range(len(matrix)) or next_j not in range(len(matrix[0])):27 continue28 if matrix[next_i][next_j] < matrix[i][j]:29 ans[i][j] = max(ans[i][j], self.dfs(matrix, next_i, next_j, ans) + 1)30 return ans[i][j]31 32 33 34