Repository navigation
Pathfinding Routing and Graph Algorithms
Algorithm Index | Foundations | Offline Labs
Represent intersections, routers, services, or dependencies as vertices (nodes), and connections as edges. Edges may have a weight: distance, configured administrative cost, latency estimate, financial cost, or risk score. A path's total weight is often the sum of its edges. The shortest weighted path is not necessarily the fastest real-world path. That depends on how weights were chosen and how quickly measurements change.
A road network may be directed, have one-way restrictions, turn costs, road closures, and changing travel-time estimates. Consumer navigation platforms can use A*, bidirectional search, contraction hierarchies, traffic prediction, and proprietary optimization; do not attribute a product's entire routing engine to one textbook algorithm.
Original illustrative graph; the highlighted path is minimum configured cost, not measured network latency. OSPF's SPF and BGP's policy-driven selection are separate concepts.
Consider this invented, directed weighted graph (all weights are nonnegative):
| Edge | Cost |
|---|---|
| A โ B | 2 |
| A โ C | 5 |
| B โ C | 1 |
| B โ D | 4 |
| C โ D | 2 |
From A to D, the path A โ B โ C โ D has total cost 5. A โ B โ D costs 6; A โ C โ D costs 7.
Dijkstra computes shortest paths from one source to all reachable vertices when edge weights are nonnegative.
- Initialize distance(A)=0, all other distances=infinity.
- Select the unsettled node with the smallest currently known distance.
- Relax each outgoing edge: if distance(u)+weight(u,v) improves distance(v), update distance(v) and remember predecessor u.
- Continue until the destination is finalized (single-target use) or the queue is exhausted.
- Reconstruct the path by following predecessors backward.
Trace: initialize (A 0, B โ, C โ, D โ); settle A โ B 2, C 5; settle B โ C 3, D 6; settle C โ D 5; settle D at 5. A binary-heap/adjacency-list implementation is often described as O((V+E) log V); alternative data structures or dense graphs produce different bounds.
dijkstra(graph, source):
distance[source] = 0
heap.push((0, source))
while heap not empty:
cost, node = heap.pop_min()
if cost != distance[node]: continue # stale entry
for next, weight in graph[node]:
require weight >= 0
if cost + weight < distance[next]:
distance[next] = cost + weight
predecessor[next] = node
heap.push((distance[next], next))
return distance, predecessor
Watch for: unreachable destinations, zero-weight edges, ties, stale priority-queue entries, overflow in fixed-width integers, and weight changes during computation. The example in labs checks total cost and the path against expected output.
A* orders candidate vertices by f(n) = g(n) + h(n), where g(n) is the best known cost so far and h(n) estimates the remaining cost to the goal.
- If h(n)=0, A* becomes Dijkstra's prioritization (in the standard formulation).
- An admissible heuristic does not overestimate the remaining optimal cost. For common graph-search A* variants, a consistent heuristic also helps guarantee optimality without needing to reopen finalized nodes.
- An overestimating heuristic can produce a faster-looking but suboptimal result; do not promise optimality without specifying the assumptions.
- Manhattan distance is useful for a four-direction grid with uniform step costs; Euclidean distance can work for spatial models where it is a valid lower bound.
- If an edge represents live congestion or time-dependent travel, a simple static heuristic/cost model may not be sufficient.
Cybersecurity connection: A* is an instructive way to reason about lowest-cost paths through a service-dependency or attack graph. This is model-based analysis, not a vulnerability exploit; the graph needs trustworthy edges and correctly interpreted costs.
| Algorithm | When To Use | Important Limitation |
|---|---|---|
| Breadth-first search (BFS) | Unweighted shortest path by hop count, reachability | Ignores unequal edge costs; O(V+E) on adjacency lists |
| Depth-first search (DFS) | Dependency traversal, cycle identification, components | Its first discovered path is not generally shortest |
| Dijkstra | Single-source shortest weighted paths | Requires nonnegative edge weights |
| A* | Target-oriented shortest path with useful heuristic | Optimality needs heuristic/implementation assumptions |
| BellmanโFord | Negative-weight edges and reachable negative-cycle detection | O(VE); not appropriate for negative-cycle shortest paths |
| FloydโWarshall | All-pairs shortest paths on small/dense graphs | O(Vยณ) time, O(Vยฒ) space |
| Topological sort | Order tasks in a directed acyclic graph (DAG) | Cycles mean no topological order exists |
| Minimum spanning tree (Prim/Kruskal) | Lowest-total-weight tree connecting an undirected graph | Not the same as shortest path between selected nodes |
Open Shortest Path First (OSPF) is an interior gateway protocol (IGP). Routers in an OSPF area exchange and maintain link-state information, build an area-scoped link-state database, and compute a shortest-path tree using a Dijkstra-based shortest-path-first procedure. They then derive forwarding entries, potentially including equal-cost multipath routes.
The edges' OSPF interface costs are administrative/configuration metrics, not continuous measurements of latency. A route with a lower sum of OSPF costs need not have lower observed delay. Area boundaries, summarization, reachability, equal-cost paths, and protocol rules affect the installed forwarding result.
Practical trace:
- Verify neighbors and adjacency states and the network's intended area design.
- Inspect link-state database changes, interface cost assignments, and relevant route tables.
- Identify a topology change, calculate expected SPF impact, and compare the observed forwarding result.
- Correlate with telemetry before describing the event as malicious.
Security checks: protect management access; configure appropriate OSPF authentication where supported, apply routing boundaries, and monitor unexpected adjacency/link-state changes. Even a mathematically correct SPF tree cannot compensate for forged or incorrectly trusted topology information.
Further reading: OSPFv2 RFC 2328, OSPFv3 RFC 5340.
Border Gateway Protocol (BGP) is an inter-domain path-vector routing protocol with policy-driven route selection, attributes, and AS-path information. A BGP best-path decision is not Dijkstra over the public Internet. Nor is a BGP AS-path a guaranteed measurement of geographic distance, congestion, or hop latency.
Security implications: route leaks and origin hijacks can redirect traffic. Protections include route filtering, max-prefix, monitoring, RPKI route origin validation (ROV) and operational coordination; ROV validates origin authorization, not an entire AS path or end-to-end trust.
References: BGP-4 RFC 4271, RPKI Origin Validation RFC 6811.
| Concept | Where It Helps | Distinction |
|---|---|---|
| IS-IS | Link-state interior routing | Also uses SPF-family computations, separate protocol and database |
| ECMP | Load distribution across equal-cost next hops | Selection/hash policy varies; doesn't guarantee equal latency |
| Anycast | Multiple sites advertise a shared address/prefix | Routing policy affects which site receives traffic |
| SDN path computation | Controller-aware topology and constraints | Controller state can be stale or incomplete |
| Spanning Tree Protocol (STP) | Preventing Layer 2 switching loops | Not a shortest-latency routing solution |
Use a four-node graph with weighted edges and compare calculated shortest paths before and after increasing one edge's cost. Record expected route changes. Then compare the abstract model with observations from an authorized network:
- router configuration/route tables, not assumptions about the vendor's implementation;
- interface errors, traffic volume, latency, and packet loss;
- Wireshark / packet inspection, recognizing a span/tap cannot see every routed path;
- segmentation/ACLs and Snort monitoring.
Safety: Do not alter routing cost or neighbor authentication in a production network just to reproduce a lab. Use an isolated simulated topology, saved snapshots, and a rollback plan.
Both routing and public-key infrastructure can be represented as graphs, but their acceptance rules differ. Dijkstra minimizes a chosen path cost; certificate path validation checks certificate signatures, trust anchors, names, time validity, permitted uses and policy constraints. No shortest-path algorithm can replace these security validations. See Cryptography & Trust Graphs and the repository's Applied Cryptography.
| Resource | Coverage |
|---|---|
| RFC 2328 ยง16 | OSPF's SPF calculation |
| RFC 4271 | BGP protocol |
| LAN TAPs, SPAN & Monitoring | Observe traffic without assuming full visibility |
| Network Security Architecture | VLAN, ACL, DMZ and switching |
| Incident Response | Investigate routing-related anomalies |
Algorithm Index | Main Index | Legal
๐ Source: Algorithms/graphs-and-routing.md | โ๏ธ Suggest an edit | โฌ
๏ธ Back to Algorithms
- ๐บ๏ธ Browse by Topic
- ๐ All Repository Files
- ๐งญ Learning Paths
- ๐ Master Guide
- ๐ค Glossary
- โ๏ธ Legal & Disclaimer
๐ Foundations & Learning
๐ก๏ธ Defense & Investigations
- Incident Response
- Open Source Intelligence (OSINT)
- Reverse Engineering
- Operations Security (OPSEC)
- Compliance
โ๏ธ Platforms & Infrastructure
๐ก Hardware, Wireless & Field Projects
- PNWC Cyberdeck
- Hardware Testing
- Hardware Hacking
- Software-Defined Radio
- Wardriving
- uConsole
- Space Security
๐งฐ Assessment & Field Reference
๐ฆ Downloads & Project Resources
๐๏ธ Additional Topics