矩陣中的最長上升序列——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