程序在Python中计算给定矩阵中的孤岛数
假设我们有一个二进制矩阵,我们必须找到矩阵中的孤岛数量。这里1代表土地,0代表水,因此一个岛屿是一组1s,它们相邻且周围被水包围。在这里,我们考虑的邻居只能是水平或垂直的,而不是对角线的。
所以,如果输入像
那么输出将是4。
为了解决这个问题,我们将遵循以下步骤-
定义一个功能explore()。这将需要行,列,矩阵
如果row和col不在矩阵范围内,或者matrix[row,col]为0,则
返回
matrix[row,col]:=0
探索(行+1,col,矩阵)
探索(行-1,col,矩阵)
探索(行,col+1,矩阵)
Explore(行,列-1,矩阵)
从主要方法中,执行以下操作-
如果矩阵为空,则
返回0
岛屿:=0
对于范围从0到矩阵的行数的行,请执行
如果matrix[row,col]与1相同,则
岛屿:=岛屿+1
探索(行,列,矩阵)
对于0到矩阵的列数范围内的col,请执行
回岛
让我们看下面的实现以更好地理解-
示例
class Solution:
def explore(self, row, col, matrix):
if (
row < 0 or col < 0 or row > len(matrix) - 1 or col > len (matrix[0]) - 1 or matrix[row][col] == 0):
return
matrix[row][col] = 0
self.explore(row + 1, col, matrix)
self.explore(row - 1, col, matrix)
self.explore(row, col + 1, matrix)
self.explore(row, col - 1, matrix)
def solve(self, matrix):
if not matrix:
return 0
islands = 0
for row in range(len(matrix)):
for col in range(len(matrix[0])):
if matrix[row][col] == 1:
islands += 1
self.explore(row, col, matrix)
return islands
ob = Solution() matrix = [
[1, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 1, 1, 0, 0],
[0, 0, 0, 0, 0],
[1, 1, 0, 1, 1],
[1, 1, 1, 0, 1]
]
print(ob.solve(matrix))输入项
[ [1, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 1, 1, 0, 0], [0, 0, 0, 0, 0], [1, 1, 0, 1, 1], [1, 1, 1, 0, 1] ]
输出结果
4