Skip to main content

Graph

Generic directed weighted graph. Implements an adjacency list graph with support for:
  • Breadth-first search (unweighted shortest path)
  • Dijkstra’s algorithm (weighted shortest path)
  • A* search (heuristic-guided pathfinding)

Parameters

  • Id Vertex identifier type (must be hashable)
  • IdHash Hash function for Id type (default: std::hash<Id>)
:::note Edge weights must be non-negative for Dijkstra and A* ::: :::note Self-loops and duplicate edges are supported :::

Public Methods


add_edge

inline
Add a directed edge to the graph.

Parameters

  • from Source vertex
  • to Destination vertex
  • w Edge weight (default: 1.0)
Edge from->to exists with weight w :::note If edge already exists, adds additional parallel edge :::

Example:


bfs

const
Breadth-first search from a start vertex. Returns all vertices reachable from start in BFS order. Uses O(V + E) time where V = vertices, E = edges.

Parameters

  • start Starting vertex

Returns

Vector of visited vertices in BFS order Returns empty vector if start not in graph :::note Does not consider edge weights (treats all as weight 1) :::

dijkstra

const
Dijkstra’s algorithm for shortest path. Finds the shortest path between two vertices using Dijkstra’s algorithm with a binary heap priority queue.

Parameters

  • start Starting vertex
  • end Destination vertex

Returns

PathResult if path exists, std::nullopt otherwise On success, path contains vertices from start to end cost equals sum of edge weights along path :::note Time complexity: O((V + E) log V) ::: :::note Edge weights must be non-negative :::

Example:


astar

const
A* pathfinding algorithm. Finds shortest path using heuristic-guided search. More efficient than Dijkstra when a good heuristic is available.

Parameters

  • start Starting vertex
  • end Destination vertex
  • h Heuristic function: estimated cost from node to goal Must be admissible (never overestimate)

Returns

PathResult if path exists, std::nullopt otherwise On success, path contains vertices from start to end cost equals g-score (actual cost, not f-score) :::note Time complexity: O(E log V) in best case with good heuristic ::: :::note Heuristic must be admissible for optimal results ::: :::note Edge weights must be non-negative :::

Example:

Private Attributes


adj_

Adjacency list: vertex -> list of (neighbor, weight) pairs.