Skip to content
Graph Intelligence Hub
Menu

Algorithm

Breadth-first search (BFS)

activeNeeds verification

Explores a graph level by level from a source node, visiting all nodes at distance k before distance k+1; finds shortest paths in unweighted graphs.

Definition

Intuition

Ripples spreading on a pond — everything one step away, then two steps, and so on, using a first-in-first-out queue.

Pseudocode

BFS(G, s):
  mark s; dist[s] = 0; Q = [s]
  while Q not empty:
    u = Q.pop_front()
    for v in neighbours(u):
      if v not marked:
        mark v; dist[v] = dist[u] + 1; Q.push_back(v)

Complexity

TimeO(V + E)
SpaceO(V)

Python

import networkx as nx
G = nx.karate_club_graph()
order = [v for _, v in nx.bfs_edges(G, source=0)]
dist = nx.single_source_shortest_path_length(G, 0)

Cypher (Neo4j GDS)

// Neo4j Graph Data Science (syntax varies by version)
MATCH (s:Person {name: 'Ada'})
CALL gds.bfs.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

Prerequisites
Implemented by