遍历矩阵的每个元素,如果是1那么就给岛屿数量加上1,同时用dfs或bfs去遍历该岛屿的所有邻接岛屿(其实就是遍历这个点的连通图),将所有邻接岛屿都重新标记为0,然后继续往下遍历就行。其实这个题就是在找矩阵中的连通图数量。
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 判断岛屿数量
# @param grid char字符型二维数组
# @return int整型
#
class Solution:
def solve(self , grid) -> int:
# write code here
if len(grid) == 0:
return 0
self.num = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if str(grid[i][j])=='0':
pass
else:
self.num+=1
self.dfs(grid,i,j)
return self.num
def dfs(self , grid , i , j):
grid[i][j]='0'
if i < len(grid)-1: # 往右看
if str(grid[i+1][j]) == '1':
self.dfs(grid,i+1,j)
else:
pass
if j < len(grid[0])-1: # 往下看
if str(grid[i][j+1]) == '1':
self.dfs(grid,i,j+1)
else:
pass
if i > 0: # 往左
if str(grid[i-1][j]) == '1':
self.dfs(grid,i-1,j)
else:
pass
if j > 0: # 往上
if str(grid[i][j-1]) == '1':
self.dfs(grid,i,j-1)
grid = [
[1,1,0,0,0],
[0,1,0,1,1],
[0,0,0,1,1],
[0,0,0,0,0],
[0,0,1,1,1]
]
print(Solution().solve(grid))