https://leetcode.com/problems/island-perimeter/description 463. Island Perimeter 給你一個包含0和1的二維陣列,0表示海水,1表示陸地,相連的陸地是一個島嶼, 假定恰好只會存在一個島嶼而且島嶼不存在湖,這個島的周長是多少? 思路: 1.找到所有的陸地座標,找出他的四周是海或越界的數量共有幾個,全部加總即可。 pycode: -------------------------------------------------- class Solution: def islandPerimeter(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) res = 0 dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]] for i in range(m): for j in range(n): if grid[i][j] == 0: continue for dir in dirs: y, x = i + dir[0], j + dir[1] if y == m or y < 0 or x == n or x < 0 or grid[y][x] == 0: res += 1 return res -------------------------------------------------- -- ※ 發信站: 批踢踢實業坊(ptt.org.tw), 來自: 101.138.201.230 (臺灣) ※ 文章網址: https://ptt.org.tw/Marginalman/M.1713403303.A.3DB