天天看点

力扣(leetcode) 463. 岛屿的周长 (几何应用 ) (numpy应用)

题目在这​​:https://leetcode-cn.com/problems/island-perimeter/​​

思路分析:

力扣(leetcode) 463. 岛屿的周长 (几何应用 ) (numpy应用)

这张图是二维数组

[

[0,1,0,0]

[1,1,1,0]

[0,1,0,0]

[1,1,0,0]

]

组成的。

要求周长,实际上可以发现,每个一维数组中,存在一对相邻的1的时候,就有两条边消失, 竖向同理。

所以我们设在横向和竖向共有X对相邻的1。则 消失的边为, ​

​X * 2​

​​ 条。

设二维数组中共有Y个1,即周长为 ​​

​Y * 4​

​​。

所以该岛屿的周长为 ​​

​Y * 4-X * 2​

class Solution:
    def islandPerimeter(self, grid: List[List[int]]) -> int:
        import numpy as np

        def A(grid,res,temp): # 该函数用于求相邻的1的个数。
            for i in grid: # 当前i为一维数组
                for j in range(len(i)-1):
                    if i[j] ==1 and i[j+1] == 1:
                        temp +=1
                res += temp * 2
                temp = 0
            return res

        if __name__ == '__main__':
            temp = 0 # 记录过程中连续的1
            res = 0 # 记录结果周长
            print(grid)
            ans = A(grid,res,temp) # 横向
            #转置
            print("第一个ans",ans)
            f = np.array(grid)
            f = f.T
            grid = f.tolist()

            ans += A(grid,res,temp)
            print("ans",ans)
            # res 是被磨灭的边
            msg = 0
            for i in grid:
                for j in i:
                    if j == 1:
                        msg +=1
            print("mas",msg)
            print("res",res)
            ans = msg * 4 - ans
            print(ans)
            return