矩阵中的最长上升序列——Longest Continuous Increasing Subsequence II


给定一个整数矩阵(其中,有 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 0
10         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 = 0
14         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 longest
18                 
19                 
20     def dfs(self, matrix, i, j, ans):
21         if ans[i][j] > 0:
22             return ans[i][j]
23         ans[i][j] = 1
24         for (di, dj) in self.DIR: 25             next_i, next_j = i + di, j + dj 26             if next_i not in range(len(matrix)) or next_j not in range(len(matrix[0])): 27                 continue
28 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             

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM