Depth-first search (DFS)

hip-hop, educational · 2:29

Listen on 93

Lyrics

[Verse 1]
Starting at the root, we pick a path and dive
Going deep before we spread, that's how DFS stays alive
Mark the node as visited, push it on the stack
Explore each neighbor fully before we double back
Recursive calls or iterative, both ways get it done
Visit children first completely, one by one by one

[Chorus]
Go Deep, Don't Spread - that's the DFS way
Stack it up, mark it down, visit all the way
Go Deep, Don't Spread - through the tree we roam
Backtrack when you hit the end, then find another home
DFS, DFS, diving to the core
Stack or recursion, either way explore

[Verse 2]
Three main applications keep this algorithm hot
Topological sorting when dependencies we've got
Cycle detection in a graph, DFS will find the loop
Connected components grouping, putting nodes in their troop
Time complexity linear, vertices plus edges count
Space complexity depends on how deep your tree can mount

[Chorus]
Go Deep, Don't Spread - that's the DFS way
Stack it up, mark it down, visit all the way
Go Deep, Don't Spread - through the tree we roam
Backtrack when you hit the end, then find another home
DFS, DFS, diving to the core
Stack or recursion, either way explore

[Bridge]
Pre-order, in-order, post-order traversal
DFS gives you options, take your pick for every trial
Discovery time and finish time, timestamps as you go
Parenthesis theorem shows the structure that you know
From maze solving to web crawling, DFS runs the show

[Verse 3]
Implementation choices, let me break it down for you
Recursive feels natural but the stack might overflow too
Iterative with explicit stack gives you more control
Mark visited in a set or boolean array to reach your goal
Colors work for tracking: white, gray, black progression
Forward, back, and cross edges tell the graph's confession

[Chorus]
Go Deep, Don't Spread - that's the DFS way
Stack it up, mark it down, visit all the way
Go Deep, Don't Spread - through the tree we roam
Backtrack when you hit the end, then find another home
DFS, DFS, diving to the core
Stack or recursion, either way explore

[Outro]
When breadth-first goes wide, DFS goes deep
Memory efficient path, promises to keep
From root to leaf completely, then backtrack and repeat
DFS mastery, now your toolkit's complete

← Breadth-first search (BFS) | Dijkstra's algorithm →