Depth First Search
MediumFollow one branch as deep as it goes, then backtrack. Each fresh launch from an unvisited node is one connected component.
recursionconnectivity
TimeO(V + E)
SpaceO(V) recursion depth
Inputedges like 0-1,1-2 | start node
Depth first: go as deep as possible before backing up.
components0
1 / 23
dfs(u):
visit(u)
for v in adj[u]:
if v not visited: dfs(v)
for each node: if not visited: dfs(node) // counts components
Why it matters
DFS answers connectivity, cycles and ordering. It does not give shortest paths.
Keyboard
space play← → stepr restartctrl K search
More in Graphs
Next visualiser
Dijkstra Shortest Path