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.
object Lesson {
def main(args: Array[String]): Unit = {
var neighbours = Array(2, 3, 0)
var i = 0
var degree = 0
while (neighbours(i) != 0) {
degree += 1
i += 1
}
println(degree)
}
}
2
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?
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?
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?
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.