※ 引述《Rushia (早瀬ユウカの体操服 )》之銘言: : 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 : -------------------------------------------------- 思路: dfs 然後速度跟空間都超爛 然後還很難寫 早知道直接迴圈 Python Code: class Solution: def islandPerimeter(self, grid: List[List[int]]) -> int: def dfs(x,y): nonlocal result,visited dx = [1,-1,0,0] dy = [0,0,1,-1] visited.add((x,y)) if grid[x][y] == 1: result += 4 for i in range(4): new_x = x + dx[i] new_y = y + dy[i] if new_x<m and new_x>=0 and new_y<n and new_y>=0: if grid[new_x][new_y] == 1: result -= 1 if (new_x,new_y) not in visited: dfs(new_x,new_y) m,n=len(grid),len(grid[0]) x = 0 y = 0 result = 0 visited = set() for i in range(m): for j in range(n): if grid[i][j] == 1: x = i y = j break dfs(x,y) return result -- ※ 發信站: 批踢踢實業坊(ptt.org.tw), 來自: 140.119.235.6 (臺灣) ※ 文章網址: https://ptt.org.tw/Marginalman/M.1713409045.A.31B
SecondRun: 大師 04/18 11:07
DJYOSHITAKA: 大師 別捲了 04/18 11:11
digua: 大師 04/18 11:11
sustainer123: 再不卷我就要去北車乞討了 04/18 11:12