Skip to main content

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:
  1. Start from the source node
  2. Visit all neighbors at distance 1
  3. Then visit all neighbors at distance 2
  4. Continue until the target is found
This guarantees finding the path with the minimum number of edges (hops).

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

Here’s how to run the query using the SDKs or curl

Example 2: Social network degree of separation

Here’s how to run the query using the SDKs or curl

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.

ShortestPathDijkstras

Find weighted shortest paths with custom calculations

ShortestPathAStar

Heuristic-guided pathfinding

Overview

Compare all shortest path algorithms

Graph Traversals

Other traversal operations