Lesson contents

Graphs and adjacency lists

A graph records connections between vertices. An adjacency list stores the neighbours of each vertex. A table of all possible pairs is another representation.

Simple example

Room 1 has direct doors to rooms 2 and 3. Print how many neighbours room 1 has.

Start1→2,3
Result2
lesson.zig
const std = @import("std");

fn show(value: i64) !void {
    var buffer: [64]u8 = undefined;
    var writer = std.fs.File.stdout().writer(&buffer);
    try writer.interface.print("{d}\n", .{value});
    try writer.interface.flush();
}

pub fn main() !void {
    const neighbours = [_]i64{2, 3, 0};
    var i: i64 = 0;
    var degree: i64 = 0;
    while (neighbours[@intCast(i)] != 0) {
        degree += 1;
        i += 1;
    }
    try show(degree);
}
Output
2
Advertisements

Everyday examples

Read a walking map

Paths connect A to B and A to C in both directions. Which places are one step from A?

StartA↔B A↔C
ResultB C

Read A’s neighbour list. Record each undirected path in both endpoint lists.

Check a one-way bus link

There is a bus from stop 3 to stop 5. The timetable shows no return bus. Does the arrow prove a service from 5 to 3?

Start3→5
Result∅

No. Store each direction separately. An outgoing connection at 3 does not create one at 5.

Keep an isolated member

A club lists students 1, 2 and 3. Only 1 and 2 are project partners. Does 3 still belong in the graph?

Start1↔2 3
Result3

Yes. Keep a vertex with an empty neighbour list so the roster still includes the student.

Cost and limits

An adjacency list uses space proportional to vertices plus edges. A square adjacency matrix uses space proportional to the square of the vertex count and allows direct edge lookup.