题目描述
给你一个由 '1'
(陆地)和 '0'
(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例 1:
输入:grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] 输出:1
示例 2:
输入:grid = [ ["1","1","0","0","0"], ["1","1","0","0","0"], ["0","0","1","0","0"], ["0","0","0","1","1"] ] 输出:3
思路
dfs模版题
/* 代码随想录
这里大家应该能看出区别了,无疑就是版本一中 调用dfs 的条件判断 放在了 版本二 的 终止条件位置上。
版本一的写法是 :下一个节点是否能合法已经判断完了,传进dfs函数的就是合法节点。
版本二的写法是:不管节点是否合法,上来就dfs,然后在终止条件的地方进行判断,不合法再return。
理论上来讲,版本一的效率更高一些,因为避免了 没有意义的递归调用,在调用dfs之前,就做合法性判断。 但从写法来说,可能版本二 更利于理解一些。(不过其实都差不太多)
很多同学看了同一道题目,都是dfs,写法却不一样,有时候有终止条件,有时候连终止条件都没有,其实这就是根本原因,两种写法而已。
*/
class Solution(object):
def __init__(self):
self.direction = [(0,1),(-1,0),(1,0),(0,-1)]
def dfs(self, grid, i, j, rows, cols, mark):
mark[i][j] = True
for dir in self.direction:
row = i+dir[0] # 这里需要新定义一个变量
col = j+dir[1]
if row>=0 and row<rows and col>=0 and col<cols and mark[row][col]==False and grid[row][col]=='1':
self.dfs(grid, row, col, rows, cols, mark)
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
rows = len(grid)
cols = len(grid[0])
mark = [[False]*cols for _ in range(rows)]
count = 0
for i in range(rows):
for j in range(cols):
if not mark[i][j] and grid[i][j]=='1':
count+=1
self.dfs(grid, i, j, rows, cols, mark)
return count
if __name__ == '__main__':
s=Solution()
grid = [
["1", "1", "0", "0", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "1", "0", "0"],
["0", "0", "0", "1", "1"]
]
print(s.numIslands(grid))