Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Graphs/Graph BFS / DFS

Technique

Multi-source BFS

Seed the BFS queue with all sources at distance 0 so one pass gives every cell's distance to its nearest source.

Learn firstGraph BFS / DFS
0%
mastery
0/9 solved
Practise nextMonsters
IdeaPracticePitfalls

Recognise it

The signal

distance to nearest X for every cell

  1. 1Brute force

    BFS from each source separately: O(k * V).

  2. 2The observation

    Per-source BFS: a virtual super-source joins them in one search.

  3. 3Why it works

    Cells are dequeued in non-decreasing distance to the nearest source.

Reach for it when

  • +spreading processes (rotting, fire)
  • +boundary-first reverse search

Not when

  • ×weighted spread (multi-source dijkstra)
  • ×need the distance to a specific source

Practice

Next

Monsters

0/9 solved
  • MonstersCSESMedium
  • Rotting OrangesAmazon, UberMedium
  • 01 MatrixGoogle, UberMedium
  • Walls and GatesPremiumMedium
  • Rotting OrangesIntuitOAMedium
  • Paths Avoiding Breach RadiusD. E. ShawOAMedium
  • Pacific Atlantic Water FlowGoogle, AmazonMedium
  • Nearest Opposite ParityCodeforces1900
  • Nearest ShopsCSESHard

Pitfalls

Misconceptions

  • !simulating minute by minute with full grid rescans
Go deeper1 combinations · resources

Combinations

  • Multi-source BFS+Graph BFS / DFS

    escape before the fire/monsters reach a cell

    Multi-source BFS:
    computes earliest arrival of monsters/fire
    Graph BFS / DFS:
    BFS for the player constrained by those times

    Monsters

Resources

  • Graph Theory playlistWilliam Fiset · video
  • Graph TraversalUSACO Guide · course
  • Disjoint Set Unioncp-algorithms · article
  • Dijkstracp-algorithms · article
  • Topological sortingcp-algorithms · article
  • Shortest paths visualizerVisuAlgo · tool
  • Graph cheatsheetTech Interview Handbook · article
TodayReviewPatternsProblems