用 Python 编写程序来查找岛屿形状的周长
pythonserver side programmingprogramming更新于 2026/1/17 6:04:17
假设我们有一个二进制矩阵,其中 0 表示空单元格,1 表示形成形状的块,现在我们必须找到该形状的周长。该形状内部不会有任何孔。
因此,如果输入如下
| 0 | 0 | 0 | 0 |
| 0 | 0 | 1 | 1 |
| 0 | 0 | 1 | 1 |
| 0 | 1 | 1 | 0 |
| 0 | 1 | 1 | 0 |
| 0 | 0 | 0 | 0 |
则输出将是14.
为了解决这个问题,我们将遵循以下步骤 −
d := 0
周长 := 0
高度 := 矩阵的行数
长度 := 矩阵的列数
对于矩阵中的每一行,执行
c := 0
对于行中的每个值,执行
如果值与 1 相同,则
环绕 := 4
如果 c 与长度 - 1 不同,则
如果 matrix[d, c + 1] 与 1 相同,则
surround := surrounded - 1
如果 c 不等于 0,则
如果 matrix[d, c - 1] 与 1 相同,则
surround := surrounded - 1
如果 d 与 height - 1 不同,则
如果 matrix[d + 1, c] 与 1 相同,则
surround := surrounded - 1
如果 d 不等于 0,则
如果 matrix[d - 1, c] 等于 1,则
surround := surrounded - 1
perimeter := perimeter + surrounded
c := c + 1
d := d + 1
返回 perimeter
让我们看看下面的实现以便更好地理解 −
示例
class Solution: def solve(self, matrix): d = 0 perimeter = 0 height = len(matrix) length = len(matrix[0]) for line in matrix: c = 0 for val in line: if val == 1: surround = 4 if c != length - 1: if matrix[d][c + 1] == 1: surround -= 1 if c != 0: if matrix[d][c - 1] == 1: surround -= 1 if d != height - 1: if matrix[d + 1][c] == 1: surround -= 1 if d != 0: if matrix[d - 1][c] == 1: surround -= 1 perimeter += surround c += 1 d += 1 return perimeter ob = Solution() matrix = [ [0,0,0,0,0], [0,0,1,1,1], [0,0,1,1,0], [0,1,1,1,0], [0,0,0,0,0] ] print(ob.solve(matrix))
输入
matrix = [ [0,0,0,0,0], [0,0,1,1,1], [0,0,1,1,0], [0,1,1,1,0], [0,0,0,0,0]]
输出
14
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

