leetcode 695. 島嶼的最大面積python
阿新 • • 發佈:2018-11-07
給定一個包含了一些 0 和 1的非空二維陣列 grid
, 一個 島嶼 是由四個方向 (水平或垂直) 的 1
(代表土地) 構成的組合。你可以假設二維矩陣的四個邊緣都被水包圍著。
找到給定的二維陣列中最大的島嶼面積。(如果沒有島嶼,則返回面積為0。)
示例 1:
[[0,0,1,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,1,1,0,1,0,0,0,0,0,0,0,0], [0,1,0,0,1,1,0,0,1,0,1,0,0], [0,1,0,0,1,1,0,0,1,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,0,0,0,0,0,0,1,1,0,0,0,0]]
對於上面這個給定矩陣應返回 6
。注意答案不應該是11,因為島嶼只能包含水平或垂直的四個方向的‘1’。
示例 2:
[[0,0,0,0,0,0,0,0]]
對於上面這個給定的矩陣, 返回 0
。
注意: 給定的矩陣grid
的長度和寬度都不超過 50。
解題思路:
很明顯看出是利用DFS解:遍歷二維陣列,當值為1時開始dfs,搜尋的時候有上下左右四個方向,每當走過一個相鄰的1(島嶼)就標記一下(改成-1),這樣下次就不會走之前走過的島嶼了。
class Solution(object): nextStep = [[0, 1], [1, 0], [0, -1], [-1, 0]] step = 0 def maxAreaOfIsland(self, grid): """ :type grid: List[List[int]] :rtype: int """ res = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 1: self.step = 0 self.dfs(grid, i, j) res = max(res, self.step) return res def dfs(self, grid, x, y): """ :type grid: List[list[int]] :type x: int :type y: int :rtype : None """ if x < 0 or y < 0 or x > len(grid) - 1 or y > len(grid[0]) - 1 or grid[x][y] != 1: return grid[x][y] = -1 self.step += 1 for i in range(len(self.nextStep)): self.dfs(grid, x + self.nextStep[i][0], y + self.nextStep[i][1])