Lab 11 – Graphs
Part 1 – A graph class¶
Task 1 – Adjacency lists¶
Vertices are numbered 0 .. n-1; adj.get(v) is the list of the neighbours of v. (The
examples of the slides number their vertices from 1, so we create one vertex more and do
not use vertex 0.)
class Graph {
int n;
List<List<Integer>> adj = new ArrayList<>();
Graph(int n) { /* ToDo: n empty lists */ }
void addEdge(int v, int w) { /* ToDo: v -> w */ }
void addUndirectedEdge(int v, int w) { /* ToDo: both directions */ }
void printLists(int from) { /* ToDo */ }
}Solution
int n; // vertices 0 .. n-1
List<List<Integer>> adj = new ArrayList<>();
Graph(int n) {
this.n = n;
for (int v = 0; v < n; v++)
adj.add(new ArrayList<>());
}
void addEdge(int v, int w) { // directed: v -> w
adj.get(v).add(w);
}
void addUndirectedEdge(int v, int w) {
adj.get(v).add(w);
adj.get(w).add(v);
}
void printLists(int from) {
for (int v = from; v < n; v++)
System.out.println(v + ": " + adj.get(v));
}Task 2 – Breadth-first search¶
bfsOrder(s) returns the vertices in the order BFS visits them; bfsDistances(s) returns
the number of edges from s to every vertex (-1 if unreachable). Use
Queue<Integer> q = new ArrayDeque<>();.
🚩 Mark a vertex as visited when it is enqueued, not when it is dequeued, or it may enter the queue several times.
Solution
List<Integer> bfsOrder(int s) {
List<Integer> order = new ArrayList<>();
boolean[] seen = new boolean[n];
Queue<Integer> q = new ArrayDeque<>();
seen[s] = true;
q.offer(s);
while (!q.isEmpty()) {
int v = q.poll();
order.add(v);
for (int w : adj.get(v))
if (!seen[w]) {
seen[w] = true; // mark when enqueued, not when dequeued
q.offer(w);
}
}
return order;
}
int[] bfsDistances(int s) {
int[] dist = new int[n];
Arrays.fill(dist, -1); // -1: not reached
Queue<Integer> q = new ArrayDeque<>();
dist[s] = 0;
q.offer(s);
while (!q.isEmpty()) {
int v = q.poll();
for (int w : adj.get(v))
if (dist[w] == -1) {
dist[w] = dist[v] + 1;
q.offer(w);
}
}
return dist;
}Task 3 – Depth-first search¶
Visit a vertex, then recursively each unvisited neighbour, in the order of the lists.
Solution
List<Integer> dfsOrder(int s) {
List<Integer> order = new ArrayList<>();
dfs(s, new boolean[n], order);
return order;
}
private void dfs(int v, boolean[] seen, List<Integer> order) {
seen[v] = true;
order.add(v);
for (int w : adj.get(v))
if (!seen[w])
dfs(w, seen, order); // go deep first, backtrack at dead ends
}Task 4 – Topological sort (Kahn’s algorithm)¶
Compute the in-degrees, enqueue the vertices of in-degree 0, then repeatedly dequeue a vertex, output it, and decrement the in-degree of its successors. If some vertices are never output, the graph has a cycle.
Solution
List<Integer> topoSort(int from) { // vertices from .. n-1
int[] in = new int[n];
for (int v = from; v < n; v++)
for (int w : adj.get(v))
in[w]++;
Queue<Integer> q = new ArrayDeque<>();
for (int v = from; v < n; v++)
if (in[v] == 0) q.offer(v);
List<Integer> order = new ArrayList<>();
while (!q.isEmpty()) {
int v = q.poll();
order.add(v);
for (int w : adj.get(v))
if (--in[w] == 0) q.offer(w);
}
if (order.size() < n - from) {
System.out.println("cycle: no topological order");
return null;
}
return order;
}Test your graph¶
The graphs of the slides: the undirected graph of the BFS slides, the directed graph of the DFS slide, and the DAG .
Graph g = new Graph(7); // vertices 1..6 (0 is not used)
int[][] edges = {{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 6}, {3, 4}, {3, 5},
{3, 6}, {4, 5}};
for (int[] e : edges)
g.addUndirectedEdge(e[0], e[1]);
g.printLists(1);
System.out.println("BFS from 1: " + g.bfsOrder(1));
System.out.println("distances: " + Arrays.toString(g.bfsDistances(1)));
Graph d = new Graph(7); // the directed graph of the DFS slide
int[][] arcs = {{1, 2}, {1, 3}, {2, 4}, {2, 6}, {4, 5}};
for (int[] e : arcs)
d.addEdge(e[0], e[1]);
System.out.println("DFS from 1: " + d.dfsOrder(1));
Graph dag = new Graph(8); // v1..v7 of the topological-sort slides
int[][] deps = {{1, 2}, {1, 3}, {1, 4}, {2, 4}, {2, 5}, {3, 6}, {4, 3}, {4, 6},
{4, 7}, {5, 4}, {5, 7}, {7, 6}};
for (int[] e : deps)
dag.addEdge(e[0], e[1]);
System.out.println("topological order: " + dag.topoSort(1));
dag.addEdge(6, 1); // creates a cycle
System.out.println("with 6 -> 1: " + dag.topoSort(1));Expected output:
1: [2, 3, 4]
2: [1, 3, 6]
3: [1, 2, 4, 5, 6]
4: [1, 3, 5]
5: [3, 4]
6: [2, 3]
BFS from 1: [1, 2, 3, 4, 6, 5]
distances: [-1, 0, 1, 1, 1, 2, 2]
DFS from 1: [1, 2, 4, 5, 6, 3]
topological order: [1, 2, 5, 4, 3, 7, 6]
cycle: no topological order
with 6 -> 1: null(distances starts with vertex 0, which is not used.)
Task 5 – The final-exam matrix question¶
Given an adjacency matrix, decide whether the graph is directed (the matrix is not symmetric), count the vertices and the edges, and find the sinks (out-degree 0) and the sources (in-degree 0).
Solution
static void analyse(int[][] M, String names) {
int n = M.length, edges = 0;
boolean symmetric = true;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
edges += M[i][j];
if (M[i][j] != M[j][i]) symmetric = false;
}
System.out.println(symmetric ? "undirected" : "directed");
System.out.println(n + " vertices, " + edges + " edges");
for (int v = 0; v < n; v++) {
int out = 0, in = 0;
for (int w = 0; w < n; w++) { out += M[v][w]; in += M[w][v]; }
if (out == 0) System.out.println("sink: " + names.charAt(v));
if (in == 0) System.out.println("source: " + names.charAt(v));
}
}int[][] M = {{0, 1, 0, 0, 1}, // the final-exam matrix
{0, 0, 0, 0, 0},
{1, 0, 0, 0, 1},
{1, 1, 1, 0, 0},
{0, 1, 0, 0, 1}};
analyse(M, "ABCDE");Expected output:
directed
5 vertices, 9 edges
sink: B
source: DPart 2 – Use the JDK¶
Challenge 1 – The route with the fewest flights¶
Run BFS from s and remember, for every city, the city it was reached from
(Map<String, String> parent). Then walk back from t to s and reverse the walk with
addFirst.
Solution
static List<String> route(Map<String, List<String>> g, String s, String t) {
Map<String, String> parent = new HashMap<>(); // also the "visited" mark
Queue<String> q = new ArrayDeque<>();
parent.put(s, null);
q.offer(s);
while (!q.isEmpty()) {
String v = q.poll();
if (v.equals(t)) break;
for (String w : g.getOrDefault(v, List.of()))
if (!parent.containsKey(w)) {
parent.put(w, v);
q.offer(w);
}
}
if (!parent.containsKey(t)) return null; // unreachable
LinkedList<String> path = new LinkedList<>();
for (String v = t; v != null; v = parent.get(v))
path.addFirst(v); // walk back to s
return path;
}Map<String, List<String>> flights = new HashMap<>();
String[][] legs = {{"R", "J"}, {"R", "D"}, {"J", "C"}, {"J", "D"}, {"D", "I"},
{"C", "I"}, {"C", "L"}, {"I", "L"}};
for (String[] f : legs) { // flights go both ways
flights.computeIfAbsent(f[0], k -> new ArrayList<>()).add(f[1]);
flights.computeIfAbsent(f[1], k -> new ArrayList<>()).add(f[0]);
}
System.out.println(route(flights, "R", "L"));
System.out.println(route(flights, "D", "C"));Expected output:
[R, J, C, L]
[D, J, C]Challenge 2 – Count the islands¶
In a grid of '1' (land) and '0' (water), count the groups of land cells joined up,
down, left or right. Each unvisited land cell starts a new island; flood it with an
ArrayDeque<int[]> used as a stack.
Solution
static int islands(String[] grid) {
int R = grid.length, C = grid[0].length(), count = 0;
boolean[][] seen = new boolean[R][C];
int[] dr = {1, -1, 0, 0}, dc = {0, 0, 1, -1};
for (int r = 0; r < R; r++)
for (int c = 0; c < C; c++) {
if (grid[r].charAt(c) != '1' || seen[r][c]) continue;
count++; // a new island: flood it
Deque<int[]> st = new ArrayDeque<>();
st.push(new int[]{r, c});
seen[r][c] = true;
while (!st.isEmpty()) {
int[] p = st.pop();
for (int k = 0; k < 4; k++) {
int x = p[0] + dr[k], y = p[1] + dc[k];
if (x >= 0 && x < R && y >= 0 && y < C
&& grid[x].charAt(y) == '1' && !seen[x][y]) {
seen[x][y] = true;
st.push(new int[]{x, y});
}
}
}
}
return count;
}String[] grid = {"11000",
"11001",
"00101",
"00011"};
System.out.println(islands(grid) + " islands");Expected output:
3 islandsChallenge 3 – A valid course schedule¶
Given pairs “a must be taken before b”, return an order in which all the courses can be
taken, or null if it is impossible. This is Kahn’s algorithm on named vertices; use
TreeMaps so the result is always the same.
Solution
// prerequisites: {a, b} means "a must be taken before b"
static List<String> schedule(String[][] prereq) {
Map<String, List<String>> g = new TreeMap<>(); // sorted: a fixed order
Map<String, Integer> in = new TreeMap<>();
for (String[] p : prereq) {
g.computeIfAbsent(p[0], k -> new ArrayList<>()).add(p[1]);
g.computeIfAbsent(p[1], k -> new ArrayList<>());
in.merge(p[1], 1, Integer::sum);
in.putIfAbsent(p[0], 0);
}
Queue<String> q = new ArrayDeque<>();
for (String c : in.keySet())
if (in.get(c) == 0) q.offer(c);
List<String> order = new ArrayList<>();
while (!q.isEmpty()) {
String c = q.poll();
order.add(c);
for (String next : g.get(c))
if (in.merge(next, -1, Integer::sum) == 0) // one prerequisite less
q.offer(next);
}
return order.size() == in.size() ? order : null; // null: a cycle
}System.out.println(schedule(new String[][]{{"CS1301", "CS2301"}, {"CS2301", "CS2311"},
{"CS2311", "CS3401"}, {"MATH", "CS3401"}}));
System.out.println(schedule(new String[][]{{"A", "B"}, {"B", "C"}, {"C", "A"}}));Expected output:
[CS1301, MATH, CS2301, CS2311, CS3401]
null