Python程式:查詢島嶼形狀的周長


假設我們有一個二進位制矩陣,其中 0 表示空單元格,1 表示形成形狀的塊,現在我們必須找到形狀的周長。該形狀內部不會包含任何孔。

因此,如果輸入類似於

00000
00111
00110
01110
00000

則輸出將為 14。

為了解決這個問題,我們將遵循以下步驟:

  • d := 0

  • perimeter := 0

  • height := 矩陣的行數

  • length := 矩陣的列數

  • 對於矩陣中的每一行,執行以下操作:

    • c := 0

    • 對於行中的每個值,執行以下操作:

      • 如果值與 1 相同,則

        • surround := 4

        • 如果 c 與 length - 1 不相同,則

          • 如果 matrix[d, c + 1] 與 1 相同,則

            • surround := surround - 1

        • 如果 c 與 0 不相同,則

          • 如果 matrix[d, c - 1] 與 1 相同,則

            • surround := surround - 1

        • 如果 d 與 height - 1 不相同,則

          • 如果 matrix[d + 1, c] 與 1 相同,則

            • surround := surround - 1

        • 如果 d 與 0 不相同,則

          • 如果 matrix[d - 1, c] 與 1 相同,則

            • surround := surround - 1

        • perimeter := perimeter + surround

        • 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

更新於: 2020年10月9日

385 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.