Skip to Content
Read

Graphs

Vertex domains, Graph.undirected, bfs, components, dijkstra, topo and grids.

A graph problem names its vertices 1..n and lists m edges. In CP Lang the vertices are a domain, the edges are read as records, and the standard searches return a table over that domain, so a vertex can't be confused with an edge index or a distance.

Reading a graph

Declare the vertex domain from n, read the edges as (u: V, v: V) records, and build the graph once. bfs returns the distance to every vertex as ?Int: None means unreachable, so there is no -1 or INF inside the program, only at the output:

Output
Press Run (Ctrl+Enter).

Reading an edge (u: V, v: V) checks that both ends are in 1..=n, and g[u] lists the neighbours of u. Graph stores every edge in one flat array, so building it allocates once.

Connected components

components gives a fresh domain C with one value per component, and comp[v] names the component of v. Its count is C.len:

Output
Press Run (Ctrl+Enter).

Because C is its own domain, an array [C]Int of component sizes can't be indexed by a vertex by mistake.

Weighted shortest paths

Add a weight to the edge record and use dijkstra. Its sources are (vertex, starting distance) pairs, so a multi-source search is the same call with more pairs. p.path(t) is the vertices of a shortest path, or None:

Output
Press Run (Ctrl+Enter).

Ordering a DAG

topo returns the vertices with every edge pointing forward, or None when there is a cycle:

Output
Press Run (Ctrl+Enter).

Grids are graphs too

A cell (r, c) of a grid over domains R and Col is a vertex. Instead of building a graph, pass a function from a cell to its neighbours: c.adj4 yields the up to four cells next to c that are inside the grid, so there is no bounds check to forget:

Output
Press Run (Ctrl+Enter).

The same function form works for any implicit graph: states of a puzzle, numbers reachable by allowed moves, and so on.

Finding the rest

The graph reference has scc, bridges, two_color, bellman_ford, floyd_warshall, euler_walk and 2-SAT, each with its cost. Trees (Rooted, LCA, tree DP) are in std.tree.

Problem: Fewest hops

Given an undirected graph, print the fewest edges on a path from vertex 1 to vertex n, or -1. With n = 5 and edges 1-2, 2-3, 3-5, 1-4, 4-5 the answer is 2.

6 tests · Ctrl+Enter
Hints

bfs(g, [V(1)]) is the whole search; ?? -1 turns "unreachable" into the output format at the last moment.

Next: Dynamic programming.

Lints for these patterns

cpl lint, the editor and the playground flag the hand-written versions of what this chapter teaches:

On this page