Leetcode 200. Number of Islands
题目
解法1:DFS
每次遇到1时进行dfs,并将访问到连在一起的1都进行mark。总共进行DFS的次数就是island的个数
python代码:
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
def helper(i,j):
if i<0 or i>=m or j<0 or j>=n or grid[i][j]!='1':
return
#visited.add((i,j))
grid[i][j] = '0'
helper(i+1,j)
helper(i-1,j)
helper(i,j-1)
helper(i,j+1)
if not grid or not grid[0]:
return 0
m = len(grid)
n = len(grid[0])
#visited = set()
count = 0
for i in range(m):
for j