用 Python 编写程序,找出不能离开的岛屿数量
pythonserver side programmingprogramming更新于 2026/1/19 13:00:17
假设我们有一个二进制矩阵。这里 1 代表陆地,0 代表水域。我们可以从任何陆地向上、向下、向左或向右移动,但不能沿对角线移动到另一个陆地单元或离开矩阵。我们必须找出不能离开矩阵的土地单元数量。
因此,如果输入如下
| 0 | 0 | 0 | 1 |
| 0 | 1 | 1 | 0 |
| 0 | 1 | 1 | 0 |
| 0 | 0 | 0 | 0 | 0 | 1 |
那么输出将是 4,因为中间有 4 个土地方格,我们无法从这些方格离开矩阵。
要解决为此,我们将遵循以下步骤 −
- q := 当 matrix[i, j] 为土地时,每行 i 和列的对 (i, j) 列表 i 和 j 是边界索引
- idx := 0
- 对于 q 中的每一对 (x, y),执行
- matrix[x, y] := 0
- 当 idx < q 的大小,执行
- x, y := q[idx]
- 对于 [(-1, 0) ,(0, -1) ,(0, 1) ,(1, 0) ] 中的每个 (dx, dy),执行
- nx := x + dx
- ny := y + dy
- 如果 0 <= nx < 矩阵的行数且 0 <= ny < 矩阵[nx]的列数且矩阵[nx, ny]为 1,则
- 矩阵[nx, ny] := 0
- 在 q 末尾插入 (nx, ny)
- idx := idx + 1
- 返回矩阵所有元素的总和
示例
让我们看看下面的实现以便更好地理解 −
def solve(matrix): q = [(i, j) for i in range(len(matrix)) for j in range(len(matrix[i])) if matrix[i][j] and (i == 0 or i == len(matrix) - 1 or j == 0 or j == len(matrix[i]) - 1)] idx = 0 for x, y in q: matrix[x][y] = 0 while idx < len(q): x, y = q[idx] for dx, dy in [(-1, 0), (0, -1), (0, 1), (1, 0)]: nx, ny = x + dx, y + dy if 0 <= nx < len(matrix) and 0 <= ny < len(matrix[nx]) and matrix[nx][ny]: matrix[nx][ny] = 0 q.append((nx, ny)) idx += 1 return sum(sum(row) for row in matrix) matrix = [ [0, 0, 0, 1], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 1] ] print(solve(matrix))
输入
[ [0, 0, 0, 1], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 1] ]
输出
4
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

