graphs

A graph is a pair of sets: vertices and edges An edge joins two vertices That is the whole abstraction

Then it spends a chapter on applications: spanning trees, components, shortest paths, max clique, bipartite covers, traveling salesperson Every one is a different question about the same pair of sets

Vocabulary that saves time

  • adjacent: two vertices joined by an edge
  • incident: an edge touching a vertex
  • directed: (i,j) is not (j,i)
  • undirected: the two directions are the same edge

Be careful about “adjacent to” and “adjacent from” in directed graphs That precision matters when modelling service calls or host links A directed edge is a one way street Treating it as two way is how you invent connections that do not exist

Representation

#include <string>
#include <unordered_map>
#include <vector>

using Graph = std::unordered_map<std::string, std::vector<std::string>>;

Graph graph{
    {"a", {"b", "c"}},
    {"b", {"d"}},
    {"c", {"d"}},
    {"d", {}}
};

An adjacency map is readable For dense graphs a matrix is better For huge sparse graphs an adjacency list is the only sane choice

Breadth first

#include <queue>
#include <unordered_set>

std::unordered_set<std::string> bfs(const std::string &start, const Graph &graph) {
    std::unordered_set<std::string> seen;
    std::queue<std::string> q;
    q.push(start);
    while (!q.empty()) {
        auto node = q.front();
        q.pop();
        if (seen.contains(node)) continue;
        seen.insert(node);
        for (const auto &nxt : graph.at(node)) q.push(nxt);
    }
    return seen;
}

Queue based It visits by distance from the start The seen set is not optional, it is the loop guard

Depth first

void dfs(const std::string &node, const Graph &graph,
         std::unordered_set<std::string> &seen) {
    seen.insert(node);
    for (const auto &nxt : graph.at(node))
        if (!seen.contains(nxt)) dfs(nxt, graph, seen);
}

Stack based, recursively It goes as deep as it can before backtracking The seen set must be shared across calls or you will revisit forever

Choosing

  • shortest number of hops -> breadth first
  • reachability and cycle detection -> depth first
  • weighted shortest path -> priority queue based search
  • dependency order -> topological sort

Worked example

a connects to b and c, both connect to d

Breadth first from a sees a, then b and c, then d Depth first may see a, b, d, then c Both end with the same set The order is the product you are choosing

Mistakes

  • forgetting the seen set
  • treating a directed graph as undirected
  • using operator[] on the graph map and creating empty nodes by accident
  • recursing too deep and hitting the stack limit

graph.at(node) throws if the node is missing That is preferable to silently inventing a node with operator[]

Exercises

  1. Run both traversals on the example and print visit order
  2. Add a cycle from d back to a and confirm both terminate
  3. Model three services that call each other as a directed graph
  4. Explain why breadth first answers fewest hops and depth first does not

What to remember

Graphs are not about drawing circles They are about reachability, order, and cost

Posted