Graph Theory37 sections · 1633 units
Open in Course

Problem - Labyrinth

(CSES maze escape)

You have an N x M grid. '#' is wall, '.' is floor, 'A' is start, 'B' is exit. Find the shortest path from A to B, or report if impossible.

Print path length and the sequence of moves (U/D/L/R).

Common mistake: using DFS. Why does BFS matter here? DFS explores one direction fully before backtracking, so it may find a long winding path when a short direct path exists. BFS guarantees you find the path with the fewest steps because it expands all cells at distance dd before any cell at distance d+1d+1.