描述
给一个 01 矩阵,求不同的岛屿的个数。
0 代表海,1 代表岛,如果两个 1 相邻,那么这两个 1 属于同一个岛。我们只考虑上下左右为相邻。
样例
样例 1:
输入:
[
[1,1,0,0,0],
[0,1,0,0,1],
[0,0,0,1,1],
[0,0,0,0,0],
[0,0,0,0,1]
]
输出:
3
样例 2:
输入:
[
[1,1]
]
输出:
1
这一题使用宽度优先搜索来做会比较简单,当然也可以用深搜来做。 具体做法就是每检测到一个岛,就搜索下去得到完整的岛,然后把这个岛归0.要记得判断越界。
代码如下:
class Solution:
"""
@param grid: a boolean 2D matrix
@return: an integer
"""
def numIslands(self, grid):
# write your code here
count=0
from queue import Queue
q=Queue()
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]==1:
count+=1
q.put((i,j))
grid[i][j]=0
while not q.empty():
index=q.get()
x,y=index[0],index[1]
if x-1>=0 and grid[x-1][y]==1:
q.put((x-1,y))
grid[x-1][y]=0
if x+1<len(grid) and grid[x+1][y]==1:
q.put((x+1,y))
grid[x +1][y] = 0
if y-1>=0 and grid[x][y-1]==1:
q.put((x,y-1))
grid[x ][y-1] = 0
if y+1<len(grid[0]) and grid[x][y+1]==1:
q.put((x,y+1))
grid[x][y+1] = 0
return count
grid=[
[1,1,0,0,0],
[0,1,0,0,1],
[0,0,0,1,1],
[0,0,0,0,0],
[0,0,0,0,1]
]
s = Solution()
print(s.numIslands(grid))