← 返回博客列表
DoorDash

DoorDash VO:計算最近 DashMart 的距離

2025-11-27

oavoservice 原創復盤:這類「從多個源出發求最短距離」的題,面試一眼就要想到 Multi-source BFS

題目(改寫版)

給定一個二維網格,字元含義:

給定若干個查詢座標 locations,對每個位置返回到最近 DashMart 的最短步數(上下左右移動)。

關鍵思路:多源 BFS

如果對每個查詢單獨 BFS,會很慢。

更好的方法:

複雜度

Python 參考實作

from collections import deque


def build_distance_to_dashmart(grid):
    if not grid or not grid[0]:
        return []

    R, C = len(grid), len(grid[0])
    INF = 10**15
    dist = [[INF] * C for _ in range(R)]
    q = deque()

    # 多源:所有 D 入隊
    for r in range(R):
        for c in range(C):
            if grid[r][c] == 'D':
                dist[r][c] = 0
                q.append((r, c))

    # BFS
    dirs = [(1,0), (-1,0), (0,1), (0,-1)]
    while q:
        r, c = q.popleft()
        for dr, dc in dirs:
            nr, nc = r + dr, c + dc
            if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] != 'X':
                if dist[nr][nc] > dist[r][c] + 1:
                    dist[nr][nc] = dist[r][c] + 1
                    q.append((nr, nc))

    return dist


def query_locations(grid, locations):
    dist = build_distance_to_dashmart(grid)
    if not dist:
        return [-1] * len(locations)

    R, C = len(grid), len(grid[0])
    ans = []
    for r, c in locations:
        if not (0 <= r < R and 0 <= c < C):
            ans.append(-1)
            continue
        if grid[r][c] == 'X':
            ans.append(-1)
            continue
        d = dist[r][c]
        ans.append(-1 if d >= 10**15 else d)
    return ans

常見坑


DoorDash 的 VO 經常把 BFS 換成業務語言(DashMart/Restaurant),但本質還是最短路。oavoservice 會訓練你把業務描述迅速映射到「多源 BFS」。


需要面試真題? 立刻聯繫微信 Coding0201獲得真題