ENع
→BFS on grids
الدرس 20 · Graph algorithms

Multi-source and 0-1 BFS on grids

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة10 خطوات5 أسئلةIntermediate
عن هذا الدرس

A grid of cells is a graph, and breadth-first search finds the fewest moves across it. Two small changes make BFS much more useful. Start it from every source at once and one pass gives each cell its distance to the nearest source. Let moves cost 0 or 1 and a deque, with free moves pushed to the front, finds the cheapest routes without a heap. The Software lessons "Graphs" and "Graph search: BFS and DFS" cover graphs, queues and plain BFS; this lesson builds on them.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 20 · تفاعلي
01 / 10

A grid is a graph

Each square cell is a node. Its neighbours are the cells directly up, down, left and right: those are its edges. Every move costs 1, so breadth-first search (BFS) finds the fewest moves from a start cell.

grid: 4 rows × 5 columns = 20 cells (nodes)
neighbours of (r, c): (r-1, c) (r+1, c) (r, c-1) (r, c+1)
edges: 4·4 across + 3·5 down = 31 neighbour pairs

BFS on a graph with V nodes and E edges: O(V + E)
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. A grid is a graph

    Each square cell is a node. Its neighbours are the cells directly up, down, left and right: those are its edges. Every move costs 1, so breadth-first search (BFS) finds the fewest moves from a start cell.

    grid: 4 rows × 5 columns = 20 cells (nodes)
    neighbours of (r, c): (r-1, c) (r+1, c) (r, c-1) (r, c+1)
    edges: 4·4 across + 3·5 down = 31 neighbour pairs
    
    BFS on a graph with V nodes and E edges: O(V + E)
  2. Distance to the nearest source

    Now there are two sources, A and B, like two exits. For every cell we want the moves to the NEAREST one. Running BFS from A, then again from B, and keeping the smaller answer works, but costs two full passes.

    sources: A = (0,0), B = (3,4)
    want: dist(cell) = min(moves from A, moves from B)
    
    one BFS per source: k sources → k passes, O(k·(V + E))
  3. Every source starts in the queue

    Multi-source BFS does it in one pass. Before the loop, put every source in the queue and give each distance 0. A queue is first in, first out: append adds at the back, popleft takes from the front.

    q = deque(sources)          # [(0,0), (3,4)]
    for s in sources: dist[s] = 0
    
      append((0,0))  d=0
      append((3,4))  d=0
  4. Both waves take one step

    Pop A from the front: its two new neighbours get distance 1 and join the back. Pop B: the same. The queue now holds only 1s, so every cell one move from either source is handled before any cell two moves away.

    pop a cell, label each unlabelled neighbour dist + 1, append it
      popleft((0,0))  d=0
      append((1,0))  d=1
      append((0,1))  d=1
      popleft((3,4))  d=0
      append((2,4))  d=1
      append((3,3))  d=1
  5. The waves spread

    Popping the 1s labels the 2s. A neighbour that already has a number is skipped, so no cell is labelled twice. When the A wave and the B wave touch, a cell keeps the first number it gets: the one from the nearer source.

    if u not in dist: a labelled cell is never relabelled
      popleft((1,0))  d=1
      append((2,0))  d=2
      append((1,1))  d=2
      popleft((0,1))  d=1
      append((0,2))  d=2
      popleft((2,4))  d=1
      append((1,4))  d=2
      append((2,3))  d=2
      popleft((3,3))  d=1
      append((3,2))  d=2
  6. One pass, nearest distances

    The queue empties. Every cell holds its moves to the nearest source, at most 3 here. Each of the 20 cells went in and out of the queue once, so the cost is O(V + E), the same as one BFS.

    dist to the nearest source:
    0 1 2 3 3
    1 2 3 3 2
    2 3 3 2 1
    3 3 2 1 0
    
    appends: 20   pops: 20   longest queue: 8
    same as one BFS from an extra start joined to A and B
  7. Moves that cost 0 or 1

    New question. Walls rise; you may break through one for a cost of 1. Stepping onto an open cell costs 0. What is the fewest walls to break from A to each cell? Plain BFS counts moves, not walls, so it gives wrong answers.

    map (# = wall):
      A.#..
      ..#..
      ##.##
      ...#B
    
    cost of a move = 1 onto a wall, 0 onto an open cell
    edge weights are only 0 or 1
  8. Free moves go to the front

    Use a deque, a queue you can add to at both ends. Pop A. Its open neighbours cost 0 more, so appendleft puts them at the FRONT, ahead of everything. A move onto a wall costs 1, so append puts it at the back.

    dist[A] = 0, q = deque([A])
      append((0,0))  d=0
      popleft((0,0))  d=0
      appendleft((1,0))  d=0
      appendleft((0,1))  d=0
    
    w = 0 → appendleft (front)   w = 1 → append (back)
  9. The deque stays in order

    Keep popping the front. The deque only ever holds two values, d at the front and d + 1 behind, so cells come out in order of walls broken: every 0, then every 1, then every 2, B among them.

    deque holds values d … d, d+1 … d+1
    pop order of d: 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2
    appends: 20   pops: 20   longest deque: 6
  10. Two walls from A to B

    Done: B shows 2, so the best route from A to B breaks 2 walls. Like plain BFS, 0-1 BFS runs in O(V + E) time, with no heap like Dijkstra's algorithm needs.

    fewest walls to break from A:
    0 0 1 1 1
    0 0 1 1 1
    1 1 1 2 2
    1 1 1 2 2
    
    B = (3,4): 2
    Dijkstra with a binary heap: O((V + E) log V)
    0-1 BFS with a deque: O(V + E)

اختبار يتاح بعد الخطوة الأخيرة.