yog/pathfinding/unweighted

Unweighted pathfinding algorithms for graphs where all edges have equal weight.

These algorithms use Breadth-First Search (BFS) to find paths and distances based on the number of hops between nodes.

AlgorithmFunctionComplexityBest For
BFS Pathshortest_path/3O(V + E)Single-pair unweighted paths
SSADsingle_source_distances/2O(V + E)Distances from one node to all others
Unweighted APSPall_pairs_shortest_paths/1O(V(V + E))All-pairs distances in sparse graphs

Why Use Unweighted Algorithms?

If your graph doesn’t have custom edge weights (or if all weights are identical), Dijkstra and Floyd-Warshall are unnecessarily slow due to their use of priority queues or O(V³) matrices. BFS-based algorithms are the most efficient way to calculate hop-counts.

Comparison with Weighted Algorithms

FeatureUnweighted (BFS)Weighted (Dijkstra)
point-to-pointO(V + E)O((V+E) log V)
SS/APSPO(V(V + E))O(V² log V + VE)
OverheadLow (simple queue)Higher (priority queue)

Values

pub fn all_pairs_shortest_paths(
  in graph: model.Graph(n, e),
) -> dict.Dict(#(Int, Int), Int)

Computes hop-count distances between all pairs of nodes in an unweighted graph.

This implementation runs a BFS from every node, which is much more efficient than Floyd-Warshall for sparse unweighted graphs.

Time Complexity: O(V(V + E))

pub fn shortest_path(
  in graph: model.Graph(n, e),
  from start: Int,
  to goal: Int,
) -> option.Option(path.Path(Int))

Finds the shortest path (minimum hops) between two nodes in an unweighted graph.

Time Complexity: O(V + E)

Example

unweighted.shortest_path(graph, from: 1, to: 5)
// => Some(Path([1, 2, 5], 2))
pub fn single_source_distances(
  in graph: model.Graph(n, e),
  source start: Int,
) -> dict.Dict(Int, Int)

Computes the shortest distance (in hops) from a source node to all reachable nodes.

Time Complexity: O(V + E)

Example

unweighted.single_source_distances(graph, source: 1)
// => Dict([#(1, 0), #(2, 1), #(5, 2)])
Search Document