今天在做題的時候,遇到一個BFS,第一反應還是隊列,結果玄而又玄的過了,看了下其他人的代碼,發現快的全是用list做的。
差很多的那種,看情況也不是因為leetcode判題時間隨機的樣子。
傳送門 地圖分析
你現在手里有一份大小為 N x N 的『地圖』(網格) grid
,上面的每個『區域』(單元格)都用 0
和 1
標記好了。其中 0
代表海洋,1
代表陸地,你知道距離陸地區域最遠的海洋區域是是哪一個嗎?請返回該海洋區域到離它最近的陸地區域的距離。
我們這里說的距離是『曼哈頓距離』( Manhattan Distance):(x0, y0)
和 (x1, y1)
這兩個區域之間的距離是 |x0 - x1| + |y0 - y1|
。
如果我們的地圖上只有陸地或者海洋,請返回 -1
。
示例:
輸入:[[1,0,1],[0,0,0],[1,0,1]] 輸出:2 解釋: 海洋區域 (1, 1) 和所有陸地區域之間的距離都達到最大,最大距離為 2。
提示:
1 <= grid.length == grid[0].length <= 100
grid[i][j]
不是0
就是1
很簡單的BFS,從陸地開始搜索就行了。
使用隊列 : 1548 ms 兩倍,彈出隊列造成的?
import queue class Solution: def maxDistance(self, grid) -> int: dx = [0, 1, 0, -1] dy = [1, 0, -1, 0] n = len(grid) q = queue.Queue() vis = dict() max_dis = -1 for i in range(n): for j in range(n): if grid[i][j] == 1: q.put([i, j, 0]) vis[(i, j)] = 0 while not q.empty(): x, y, cnt = q.get() for i in range(4): tx = x + dx[i] ty = y + dy[i] if 0 <= tx < n and 0 <= ty < n and (tx, ty) not in vis: max_dis = max(max_dis, cnt + 1) vis[(tx, ty)] = cnt + 1 q.put([tx, ty, cnt + 1]) return max_dis
使用list: 時間是 712 ms
import queue class Solution: def maxDistance(self, grid: List[List[int]]) -> int: dx = [0,1,0,-1] dy = [1,0,-1,0] n = len(grid) q = list() vis = dict() max_dis = -1 for i in range(n): for j in range(n): if grid[i][j] == 1: q.append([i,j,0]) vis[(i,j)] = 0 if len(q) == 0: return -1 while len(vis) < n*n: tmp = [] for x,y,cnt in q: for i in range(4): tx = x + dx[i] ty = y + dy[i] if 0 <= tx < n and 0 <= ty < n and (tx,ty) not in vis: max_dis = max(max_dis, cnt+1) vis[(tx,ty)] = cnt + 1 tmp.append([tx, ty, cnt+1]) q = tmp.copy() return max_dis