程序在Python中查找岛形的周长
假设我们有一个二进制矩阵,其中0表示空单元格,1表示形成形状的块,现在我们必须找到形状的周长。该形状不会在其中保留任何孔。
所以,如果输入像
那么输出将为14。
为了解决这个问题,我们将遵循以下步骤-
d:=0
周长:=0
height:=矩阵的行数
长度:=矩阵的列数
对于矩阵中的每一行,执行
如果val与1相同,则
如果matrix[d-1,c]与1相同,则
环绕:=环绕-1
如果matrix[d+1,c]与1相同,则
环绕:=环绕-1
如果matrix[d,c-1]与1相同,则
环绕:=环绕-1
如果matrix[d,c+1]与1相同,则
环绕:=环绕-1
环绕:=4
如果c与长度不相同-1,则
如果c不等于0,则
如果d与高度-1不同,则
如果d不等于0,则
周长:=周长+周围
c:=c+1
c:=0
对于行中的每个val,执行
d:=d+1
返回周长
让我们看下面的实现以更好地理解-
示例
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