题目描述:给一个01矩阵,求不同的岛屿的个数。0代表海,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 个岛.
我们现在把目光聚焦到其中一个1上,从这个1开始,先将这个1改成0,再沿着上下左右4个方向开始遍历矩阵,遍历的方法是深度优先搜索(详见:点击打开链接),将所有遍历到的1都改成0,直到在一个1的四个方向上相邻的的元素都是0,那么停止对这个元素的深搜。这样,我们就将“一个岛屿”上的所有1都改成了0,从地图上看,这个岛屿“消失了”。那么有多少个岛屿呢?就看这样的深搜遍历有多少次(因为一次这样的深搜消去了一个岛屿),代码如下:
class Solution:
# @param {boolean[][]} grid a boolean 2D matrix
# @return {int} an integer
def numIslands(self, grid):
if len(grid) == 0 or len(grid[0]) == 0:
return 0
index1, row = 0, len(grid)
index2, col = 0, len(grid[0])
count = 0
# 二维矩阵的遍历
while index1 < row:
index2 = 0
while index2 < col:
if grid[index1][index2] == 1:
self.dfs_helper(grid, index1, index2)
count += 1
index2 += 1
index1 += 1
return count
# 深搜函数
def dfs_helper(self, grid, i, j):
# 终止条件
if i >= len(grid) or j >= len(grid[0]):
return
if grid[i][j] == 0:
return
# 1改成0
grid[i][j] = 0
# 沿4个方向深搜
if i < len(grid):
self.dfs_helper(grid, i + 1, j)
if j < len(grid[0]):
self.dfs_helper(grid, i, j + 1)
if j > 0:
self.dfs_helper(grid, i, j - 1)
if i > 0:
self.dfs_helper(grid, i - 1, j)
# Write your code here
这道题关键是对深搜算法的熟悉程度,所以,没明白的话,请详细参考之前的讲解。