Algorithm
Depth-first search (DFS)
activeNeeds verification
Explores as far as possible along each branch before backtracking; the basis for topological sorting, cycle detection and strongly connected components.
Intuition
Walking a maze with one hand on the wall, backing up only at dead ends, using a stack (or recursion).
Pseudocode
DFS(G, u):
mark u
for v in neighbours(u):
if v not marked: DFS(G, v)
Complexity
| Time | O(V + E) |
|---|---|
| Space | O(V) |
Python
import networkx as nx
G = nx.karate_club_graph()
order = list(nx.dfs_preorder_nodes(G, source=0))Cypher (Neo4j GDS)
MATCH (s:Person {name: 'Ada'})
CALL gds.dfs.stream('myGraph', {sourceNode: s})
YIELD path RETURN pathProcedure names and options vary between GDS versions; check the GDS docs for your version.
An interactive step-by-step visualizer for this algorithm is planned for phase 3.
Profile
| Time complexity | O(V + E) |
|---|---|
| Space complexity | O(V) |
Relationships
- Belongs to