Find Unweighted Shortest Paths with BFS Β
ShortestPathBFS uses breadth-first search to find the shortest path between nodes when all edges have equal weight. Itβs the fastest algorithm for unweighted graphs and is ideal when you care about minimizing the number of hops rather than total distance or cost.When using the SDKs or curling the endpoint, the query name must match what is defined in the
queries.hx file exactly.How It Works
BFS explores the graph level by level:- Start from the source node
- Visit all neighbors at distance 1
- Then visit all neighbors at distance 2
- Continue until the target is found
When to Use ShortestPathBFS
Use BFS when you want to:- Minimize hop count: Find paths with the fewest edges
- Equal edge importance: All edges are equally significant
- Social network analysis: Find degrees of separation
- Network routing: Minimize number of router hops
- Fast performance: Need the fastest shortest path algorithm
If edges have different weights (distance, cost, time), use ShortestPathDijkstras instead.
Example 1: Basic shortest path by hop count
Example 2: Social network degree of separation
Result Structure
ShortestPathBFS returns a result containing:Performance Characteristics
- Time Complexity: O(V + E) where V is vertices and E is edges
- Space Complexity: O(V) for tracking visited nodes
- Guarantee: Always finds the shortest path by hop count
- Best Case: Target is a direct neighbor (1 hop)
- Worst Case: Target requires exploring entire graph
BFS is the fastest shortest path algorithm for unweighted graphs. For weighted graphs, it may not find the optimal path.