类似与单词搜索
单词搜索
同样的配方 闭着眼睛写
DFS + 标记
class Solution:
def numIslands(self, grid):
m, n = len(grid), len(grid[0])
isUsed = [[False] * n for _ in range(m)]
# print(isUsed)
directions = [[1, 0], [-1, 0], [0, -1], [0, 1]]
Islands = 0
def dfs(i, j):
for direction in directions:
if 0 <= i+direction[0] < m and 0 <= j+direction[1] < n \
and grid[i+direction[0]][j+direction[1]] == "1"\
and isUsed[i+direction[0]][j+direction[1]] == False:
isUsed[i + direction[0]][j + direction[1]] = True
dfs(i+direction[0], j+direction[1])
for row in range(m):
for col in range(n):
if grid[row][col] == "1" and isUsed[row][col] == False:
isUsed[row][col] = True
Islands = Islands + 1
dfs(row, col)
else:
continue
return Islands