Python 3D Academyবাংলা

BFS from many starts, and graphs you never build: word ladders

🌍 In real life. A city planner wants to know, for every house, how far it is from the nearest fire station. Running a separate search from each station and taking the smallest would repeat work over and over. Instead, imagine the alarm sounding at every station at once: in minute one, the trucks reach the houses next to any station; in minute two, the next ring; and so on. Each house is reached first by its nearest station.

A second kind of puzzle: turn hit into cog one letter at a time, every step a real word: hit → hot → dot → dog → cog. The words form a graph that nobody draws; its edges are found only when needed.

The idea in one sentence: a multi-source BFS puts every start in the queue at distance 0 before the search begins, so each vertex is reached first, and labelled, by its nearest start; and an implicit graph finds a vertex's neighbours by rule (here: words that differ in one letter) instead of from a stored list.

Its words:

  • multi-source BFS: one BFS whose first layer is all the sources together
  • frontier: the vertices reached in the latest round, waiting to spread
  • implicit graph: vertices and edges defined by a rule, generated while searching
  • pattern: a word with one letter replaced by *, like h*t; two words are neighbours exactly when they share a pattern

Step by step, the street F.....F:

  1. Both stations, at 0 and 6, are distance 0; they form the first frontier.
  2. Round 1: houses 1 and 5 are reached: distance 1.
  3. Round 2: houses 2 and 4: distance 2.
  4. Round 3: house 3, reached from both sides at once: distance 3.
  5. Nothing new: done.

Why it is correct. It is ordinary BFS on a slightly bigger graph: add one imaginary "super source" with an edge of length 0 to every station. BFS from it reaches vertices in order of distance, so the first time a house is reached, it is by its nearest station, and that distance is final. Running one BFS per station would cost (number of stations) × (V + E); together, it is one O(V + E) search. The same trick spreads rot through a crate of mangoes (LeetCode 994), finds the distance to the nearest 0 in a grid (542), or the nearest gate (286).

Word ladders (LeetCode 127). The vertices are the words; two are joined when they differ in exactly one letter. Comparing every pair of words costs O(n² × L) before the search even starts. Instead, list every word under each of its patterns: hot goes under *ot, h*t and ho*. A word's neighbours are then the other words under its patterns, found in O(L) lookups. A plain BFS from the start word gives the fewest steps: every word is visited once, so the whole search costs about O(n × L²) for n words of length L.

from collections import deque


def distances(grid):                        # "F" fire stations, "." houses
    rows, cols = len(grid), len(grid[0])
    dist = [[-1] * cols for _ in range(rows)]
    queue = deque()
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == "F":           # every source starts the BFS together
                dist[r][c] = 0
                queue.append((r, c))
    while queue:
        r, c = queue.popleft()
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < rows and 0 <= nc < cols and dist[nr][nc] == -1:
                dist[nr][nc] = dist[r][c] + 1
                queue.append((nr, nc))
    return dist


for row in distances(["F..", "...", "..F"]):
    print(row)


from collections import defaultdict, deque


def ladder(start, goal, words):
    words = set(words) | {start}
    by_pattern = defaultdict(list)          # "h*t" -> every word that fits it
    for w in words:
        for i in range(len(w)):
            by_pattern[w[:i] + "*" + w[i + 1:]].append(w)
    seen, queue = {start}, deque([(start, 1)])
    while queue:
        word, count = queue.popleft()
        if word == goal:
            return count                    # words in the shortest ladder
        for i in range(len(word)):
            for nxt in by_pattern[word[:i] + "*" + word[i + 1:]]:
                if nxt not in seen:
                    seen.add(nxt)
                    queue.append((nxt, count + 1))
    return 0


print(ladder("hit", "cog", ["hot", "dot", "dog", "lot", "log", "cog"]))
print(ladder("hit", "cog", ["hot", "dot", "dog", "lot", "log"]))
The ladder counts words, so hit → hot → dot → dog → cog is 5. Without cog in the list there is no ladder: 0.

Mistakes and edge cases.

  • One BFS per source. Correct but slow: with k stations it does k times the work. Put all sources in the queue first.
  • Marking a vertex when it is popped, not when it is pushed. A vertex can then be pushed by several neighbours, and the queue grows with repeats. Mark it as soon as it is put in.
  • Counting steps instead of words. LeetCode 127 counts words in the ladder (start included); starting the count at 0 gives one less.
  • Comparing every pair of words. For 5,000 words that is 12.5 million comparisons before the search starts; patterns avoid it.
  • A goal that isn't in the word list. Then there is no ladder: return 0 instead of searching for ever.

Quiz

  1. What does this print?

    from collections import deque
    
    
    def distances(grid):                        # "F" fire stations, "." houses
        rows, cols = len(grid), len(grid[0])
        dist = [[-1] * cols for _ in range(rows)]
        queue = deque()
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == "F":           # every source starts the BFS together
                    dist[r][c] = 0
                    queue.append((r, c))
        while queue:
            r, c = queue.popleft()
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                if 0 <= nr < rows and 0 <= nc < cols and dist[nr][nc] == -1:
                    dist[nr][nc] = dist[r][c] + 1
                    queue.append((nr, nc))
        return dist
    
    
    for row in distances(["...", ".F."]):
        print(row)
  2. Why put every fire station in the queue before the BFS starts, instead of running one BFS from each?

    • One search of O(V + E) instead of one per station, and each house is still reached first by its nearest station
    • Because BFS can't start from a single vertex
    • It finds the farthest station
  3. In a word ladder, which words are listed under the pattern c*t?

    • cat, cot and cut, if they are in the list
    • cat and act
    • Every word that starts with c
  4. ladder("hit", "cog", ["hot", "dot", "dog", "lot", "log", "cog"]) should be 5 (hit, hot, dot, dog, cog), but this gives 4. Which line is wrong?

    def ladder(start, goal, words):
        words = set(words) | {start}
        by_pattern = defaultdict(list)
        for w in words:
            for i in range(len(w)):
                by_pattern[w[:i] + "*" + w[i + 1:]].append(w)
        seen, queue = {start}, deque([(start, 0)])
        while queue:
            word, count = queue.popleft()
            if word == goal:
                return count
            for i in range(len(word)):
                for nxt in by_pattern[word[:i] + "*" + word[i + 1:]]:
                    if nxt not in seen:
                        seen.add(nxt)
                        queue.append((nxt, count + 1))
        return 0

Coding tasks

  1. Write distances(grid): grid is a list of equal-length strings of F (fire station) and . (house). Return a list of lists with each square's distance (up, down, left and right moves) to the nearest station. There is at least one station.

  2. Write ladder(start, goal, words): the number of words in the shortest ladder from start to goal, changing one letter at a time, every word after start taken from words; 0 if there is none.