Skip to content
Graph Intelligence Hub
Menu

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

TimeO(V + E)
SpaceO(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 path

Procedure 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 complexityO(V + E)
Space complexityO(V)

Relationships