假设我们有两个二进制矩阵 mat1 和 mat2。这里1代表陆地,0代表水,如果有一组1(陆地)被水包围的就叫做岛。我们必须找到在 mat1 和 mat2 中存在于完全相同坐标处的岛数。
所以,如果输入像 mat1 =
1 | 0 | 1 |
1 | 0 | 0 |
1 | 0 | 0 |
和 mat2 =
1 | 0 | 1 |
1 | 0 | 0 |
1 | 0 | 1 |
那么输出将是 2,因为重叠的岛屿是,
1 | 0 | 1 |
1 | 0 | 0 |
1 | 0 | 1 |
所以有两个重叠的岛屿。
让我们看看以下实现以获得更好的理解 -
def solve(mat1, mat2): r = len(mat1) c = len(mat1[0]) last_row = r - 1 last_col = c - 1 def mark(i, j): mat1[i][j] = mat2[i][j] = 0 if i and (mat1[i - 1][j] or mat2[i - 1][j]): mark(i - 1, j) if j and (mat1[i][j - 1] or mat2[i][j - 1]): mark(i, j - 1) if j < last_col and (mat1[i][j + 1] or mat2[i][j + 1]): mark(i, j + 1) if i < last_row and (mat1[i + 1][j] or mat2[i + 1][j]): mark(i + 1, j) for i in range(r): for j in range(c): if mat1[i][j] != mat2[i][j]: mark(i, j) islands = 0 for i in range(r): for j in range(c): if mat1[i][j]: islands += 1 mark(i, j) return islands mat1 = [ [1, 0, 1], [1, 0, 0], [1, 0, 1] ] mat2 = [ [1, 0, 1], [1, 0, 0], [1, 0, 0] ] print(solve(mat1, mat2))
[ [1, 0, 1], [1, 0, 0], [1, 0, 1] ] [ [1, 0, 1], [1, 0, 0], [1, 0, 0] ]输出结果
2