ma'am audrey's lessons

ITC 120 › Final › Graphs

Graphs · Lesson 1 of 3

Graphs, and How to Store Them

This lesson teaches:Data structure

Trees let each node have one parent. Graphs remove that rule: anything can connect to anything.

By the end, you can:

  1. say what a graph is and give two ways it differs from a tree;
  2. point out a vertex's neighbors, degree (in- and out-degree for arrows), a path, a cycle, and a loop in a drawing;
  3. tell from a drawing or a matrix whether a graph is directed and whether it is weighted;
  4. write the adjacency matrix and adjacency list of a small graph, and draw a graph from either one;
  5. choose the matrix or the list for a given graph and explain why, and read Java code that stores a graph both ways.

You need: the linked lists lesson (for adjacency lists), the trees lessons, and scratch paper.

Part 1 · The idea

What a graph is

Graph

A graph is a non-linear data structure made of a set of vertices (also called nodes) and a set of edges. Each edge connects two vertices.

ABCD

Vertices: A, B, C, D · Edges: A–B, A–D, B–C, B–D

Extra: how books write a graph

Extra topic. You may see this short math form in books. Open this if you are curious.

Books often write a graph as G = (V, E): V is the set of vertices, E is the set of edges. Here, a set just means a group of items with no repeats, listed inside curly braces { }. (Sets get their own lesson later.) The graph above is V = {A, B, C, D} and E = {A–B, A–D, B–C, B–D}.

Graphs vs. trees

You already know one kind of graph: a tree is a graph with special rules (one root, every other node has exactly one parent, no cycles). A general graph drops those rules:

TreeGraph
Root?yes, oneno root
Parents?every node except the root has exactly oneno parent/child idea; a vertex can connect to any number of others
Cycles?neverallowed (you can go around and come back)
Connected?alwaysnot always; some parts can be separate

So: every tree is a graph, but not every graph is a tree.

Where you see graphs in IT

Graphs are everywhere in IT. Here are some examples:

  • Computer networks: devices (vertices) connected by cables or Wi-Fi links (edges).
  • Social media: people (vertices) and friendships (edges). "People you may know" are often friends of your friends.
  • Maps and delivery apps: places (vertices) and roads (edges), used to find a route.
  • The web: pages (vertices) and links (edges) from one page to another.
Computer networkvertices: devicesedges: cables or Wi-FirouterlaptopphoneprintertabletSocial mediavertices: peopleedges: friendships?YouAnaMigsBeaMaps and deliveryvertices: placesedges: roads (minutes)10674HomeSchoolMarketBeachThe webvertices: pagesedges: links (one way)HomeNewsEnrollSame idea every time: things + connections
The four examples as small graphs. On social media, you are not friends with Bea yet (dashed line), but two of your friends are, so the app may suggest her. On the map, the numbers are travel minutes (made-up), so it is a weighted graph. On the web, a link goes one way, so the edges are arrows (a directed graph). You will meet both words in Part 2.

Part 2 · Vocabulary

Graph terminology

These are the basic terms used with graphs. The examples refer to the small graph above. Tap any row to see it in the graph (on a computer, just point at the row).

TermMeaningExample
Vertex (node)one item in the graphA
Edgea connection between two verticesA–B
Adjacent (neighbors)two vertices joined by an edgeB and C are adjacent; A and C are not
Degreethe number of edges touching a vertexB has degree 3
Patha sequence of vertices, each joined to the next by an edgeA → B → C
Cyclea path that starts and ends at the same vertex, without repeating any edge or any other vertexA → B → D → A
Loopan edge from a vertex to itself(none here)
Connectedevery vertex can be reached from every other vertexthis graph is connected

Directed or undirected?

Graphs can be described in two ways, depending on whether edges have a direction:

Undirected

ABCD

Edges have no direction. A–B means you can go A to B and B to A. Like Facebook friends: if you are my friend, I am yours.

Directed

ABCD

Each edge is an arrow. A → B lets you go from A to B, but not back. Like following someone on TikTok: they do not have to follow you back.

In a directed graph, degree splits in two. The out-degree counts arrows leaving a vertex; the in-degree counts arrows coming in. The two pictures below show both counts for vertex A in the directed graph above:

Out-degree of A = 2

ABCD

Count the arrows leaving A (highlighted): A → B and A → D. That makes 2. In TikTok terms, this is how many accounts A follows.

In-degree of A = 1

ABCD

Count the arrows coming into A (highlighted): only C → A. That makes 1. In TikTok terms, this is how many followers A has.

Tip: look at the arrowhead. If the arrowhead touches the vertex, the arrow counts toward its in-degree; if the tail starts there, it counts toward its out-degree.

Weighted or unweighted?

74125ABCD

In a weighted graph, each edge carries a number called its weight. It can mean distance, cost, or time.

Here the weights are travel times in minutes (made-up numbers). From A to C, the path A → D → B → C takes 4 + 5 + 12 = 21 minutes, but A → B → C takes 7 + 12 = 19.

An unweighted graph has no numbers: every edge counts the same.

Where you see this: map apps

Map apps such as Google Maps and Waze store roads as a weighted graph. Here is what each part stands for:

  • Vertices: intersections and places, like your house, DOrSU, or the public market.
  • Edges: the road segments between them. A one-way street is a directed edge.
  • Weights: usually the expected travel time, updated with live traffic. That is why the app may reroute you mid-trip.

The picture below shows a small made-up map in a map app (top) and the weighted graph the app stores for it (bottom). The places and minutes are the same as in the graph above, with A as your home and C as DOrSU.

1. What you see in the map appHome (A)Plaza (B)DOrSU (C)Market (D)19 minfastest routestored as2. What the app stores: a weighted graph74125ABCDA → B → C = 7 + 12 = 19 minutes
The blue line in the app and the orange path in the graph are the same route. The app adds up the minutes along each possible path and shows the smallest total: A → B → C, 19 minutes. (Made-up map and travel times.)

To suggest a route, the app looks for the path with the smallest total weight, just like A → B → C (19 minutes) above. So the "shortest" route usually means the fastest, not the fewest kilometers. To see how a program finds it, try the mini map app in Part 8.

Loops

ABCD

C has a loop: an edge that leaves C and comes right back to C. Think of a web page that links to itself (like a "back to top" link).

Part 3 · Storing a graph, way 1

Adjacency matrix

The circles-and-lines pictures in these lessons are drawn for people: our eyes can follow the lines and see who connects to whom. A computer cannot look at a picture. It needs the same facts written down as data in memory: which vertex has an edge to which.

Where each circle sits on the page does not matter. Move the circles around and it is still the same graph, because only the connections count. So the computer stores only the connections. There are two common ways to do it: the adjacency matrix (this part) and the adjacency list (Part 4). Both hold exactly the same graph as the drawing. The matrix is stored in a 2D array, so first, a quick look at one.

First: a 2D array

In the Arrays lesson, an array was one row of slots. Some data needs a grid: rows and columns. Think of the seat plan in your classroom. To point to one seat, you say two numbers: its row and its column.

2D array

A 2D (two-dimensional) array is a grid of slots, all holding the same type. Each slot has two indexes: [row][column]. Both count from 0, like a normal array.

row ↓ / col →0123
00000
10070
20000

seats[1][2] is row 1, column 2 (the orange slot). Every other slot still holds 0.

int[][] seats = new int[3][4];   // 3 rows, 4 columns, all 0
seats[1][2] = 7;                 // row 1, column 2
System.out.println(seats[1][2]); // 7
System.out.println(seats.length);    // 3 (rows)
System.out.println(seats[0].length); // 4 (columns)

Here is how to read each line aloud:

CodeRead it as
int[][] seats = new int[3][4];"make a grid named seats with 3 rows and 4 columns." Every slot starts at 0. The two pairs of [ ] mean "rows, then columns."
seats[1][2] = 7;"go to row 1, then to column 2, and store 7 there."
seats.length"how many rows": 3.
seats[0].length"how many columns in row 0": 4.

Row first, then column

seats[2][1] is a different slot: row 2, column 1. It still holds 0.

An adjacency matrix is exactly this kind of grid. Its rows are the vertices, its columns are the same vertices again, and each slot answers one question: is there an edge from this row's vertex to this column's vertex?

Adjacency matrix

An adjacency matrix is a 2D array with one row and one column for each vertex. The cell [row][column] is 1 if there is an edge from the row vertex to the column vertex, and 0 if there is not.

ABCD
Adjacency matrix (row = from, column = to)
ABCD
A0101
B0010
C1000
D0010

How to read it: pick a row and read across. Row A is 0 1 0 1, so A has edges to B and D. To find edges coming into a vertex, read down its column: column A has a 1 in row C, so C → A.

Three things to notice

The matrix shows you the type of graph. Look for these three things:

  1. Undirected = mirror image. Every undirected edge A–B is stored twice, as [A][B] and [B][A]. So the matrix matches itself across the diagonal (it is symmetric).
  2. The diagonal means loops. Cell [C][C] is an edge from C to itself. If the diagonal is all 0, there are no loops.
  3. Weights replace the 1s. In a weighted graph, the cell stores the weight instead of 1. In this course, 0 still means "no edge". Some books write ∞ or leave the cell blank instead, because a real edge could have weight 0.

Undirected: symmetric

Adjacency matrix (row = from, column = to)
ABCD
A0101
B1011
C0100
D1100

Weighted: numbers

Adjacency matrix (row = from, column = to)
ABCD
A0704
B70125
C01200
D4500

Part 4 · Storing a graph, way 2

Adjacency list

Adjacency list

An adjacency list gives each vertex its own list of the vertices it has an edge to. The lists are often linked lists, so each one ends with null.

ABCD
A →B→D →null
B →C →null
C →A →null
D →C →null

This should look familiar: each row is a from the linked lists lesson. A's list is B → D → null, so A has edges to B and D.

For an undirected graph, each edge appears in two lists: A–B puts B in A's list and A in B's list. For a weighted graph, each cell also stores the weight, for example (B, 7).

Exam traps

  • A row (or a list) shows edges going out. To find edges coming in, read the column, or look for the vertex inside the other lists.
  • The order inside a list does not change the graph. A → B → D and A → D → B describe the same edges.
  • A vertex with an empty list (just null) has no outgoing edges, but it can still have incoming ones.

Part 5 · Play

Build your own

All three views below show the same graph. Change one and watch the others follow. Try these:

  1. In undirected mode, tap [B][E]. Two cells change. Why?
  2. Switch to directed and tap [E][D]. Now only one cell changes.
  3. Tap a diagonal cell to make a loop.

Build a graph: three views, one graph

Tap a cell in the matrix to add or remove an edge. Watch the drawing and the adjacency list change too. Try the diagonal (A to A).

Part 6 · Choosing

Matrix or list?

Both store the same graph. They differ in memory and in which questions they answer quickly:

QuestionAdjacency matrixAdjacency list
Memory usedalways vertices × vertices cells (100 vertices → 10,000 cells), even with few edgesone list per vertex, plus one cell per edge that exists (two for an undirected edge)
"Is there an edge A → B?"look at one cell: [A][B]. Fast.walk through A's list until you find B
"Who are A's neighbors?"scan the whole row, including all the 0swalk A's list: only real neighbors
Best whenthe graph is dense (many edges) or smallthe graph is sparse (few edges per vertex)

Think of your class

To record who is friends with whom in a class of 40, a matrix is a 40 × 40 grid: 1,600 boxes, mostly empty. A list is like each student writing just their friends' names on an index card. Most real graphs (social networks, roads) are sparse, so lists are used more often.

Part 7 · Your turn

Reading practice

Exams often give you only the matrix or only the list, with no drawing. Use these two views of the same graph to answer the questions. Try sketching the graph on paper first.

Adjacency matrix (row = from, column = to)
ABCDE
A00110
B10000
C01000
D01001
E00000
A →C→D →null
B →A →null
C →B →null
D →B→E →null
E →null
  1. Look at row A of the matrix. Which vertices does A have an edge to?

  2. Which vertex has no outgoing edges?

  3. Which vertex receives edges from two different vertices?

  4. Based on the matrix, this graph is:

  5. What is the out-degree of D?

  6. In any adjacency matrix, a 1 on the diagonal (for example, [C][C]) means:

Score: 0 / 6

Show the drawing
ABCDE

Part 8 · In code

Graphs in Java

In Java, we usually number the vertices 0, 1, 2, … and keep their names in a separate array. So A is 0, B is 1, C is 2, and D is 3.

Adjacency matrix: a 2D array

public class MatrixGraph {
  static char[] names = {'A', 'B', 'C', 'D'};
  static int n = names.length;
  static int[][] adj = new int[n][n];   // all 0 at first

  // undirected edge: set both cells
  static void addEdge(int from, int to) {
    adj[from][to] = 1;
    adj[to][from] = 1;   // remove this line for directed
  }

  public static void main(String[] args) {
    addEdge(0, 1);   // A - B
    addEdge(0, 3);   // A - D
    addEdge(1, 2);   // B - C
    addEdge(1, 3);   // B - D

    // neighbors of B (index 1): scan row 1
    for (int j = 0; j < n; j++) {
      if (adj[1][j] == 1) {
        System.out.print(names[j] + " ");
      }
    }
    // prints: A C D
  }
}

▶ Try it in the Programiz online compiler: tap Copy, paste it there, change public class MatrixGraph to public class Main (Programiz saves your code as Main.java, and Java needs the file name and the public class name to match), then press Run.

Here is how to read the new lines aloud:

CodeRead it as
static char[] names = {'A', 'B', 'C', 'D'};"names is an array of char values, holding A, B, C, D." A char is one character, written in single quotes: 'A'. (Double quotes, "A", make a String.) So names[1] is 'B'.
static int n = names.length;"n is the number of names": 4. Because it is static, every method in the class can use it.
static int[][] adj = new int[n][n];"make a grid named adj with n rows and n columns." Every cell starts at 0 (no edges yet). This is the 2D array from Part 3.
adj[from][to] = 1;"in row from, column to, store 1": there is now an edge from from to to.
if (adj[1][j] == 1)"if row 1 (B) has a 1 in column j": then vertex j is a neighbor of B.

Adjacency list: a list of lists

ArrayList is Java's built-in resizable array: you can keep calling add and it grows. Here, we keep one ArrayList per vertex. Each inner list plays the role of the linked lists in our pictures.

import java.util.ArrayList;

public class ListGraph {
  static char[] names = {'A', 'B', 'C', 'D'};
  static int n = names.length;
  static ArrayList<ArrayList<Integer>> list = new ArrayList<>();

  // undirected edge: add each to the other's list
  static void addEdge(int from, int to) {
    list.get(from).add(to);
    list.get(to).add(from);   // remove for directed
  }

  public static void main(String[] args) {
    for (int i = 0; i < n; i++) {
      list.add(new ArrayList<>());   // one empty list each
    }
    addEdge(0, 1);   // A - B
    addEdge(0, 3);   // A - D
    addEdge(1, 2);   // B - C
    addEdge(1, 3);   // B - D

    // neighbors of B: walk B's list only
    for (int j : list.get(1)) {
      System.out.print(names[j] + " ");
    }
    // prints: A C D
  }
}

▶ Try it in the Programiz online compiler: tap Copy, paste it there, change public class ListGraph to public class Main (Programiz saves your code as Main.java, and Java needs the file name and the public class name to match), then press Run.

Here is how to read the new lines aloud:

CodeRead it as
import java.util.ArrayList;"let this program use Java's ArrayList class." ArrayList is in Java's java.util package, so we must import it first.
ArrayList<ArrayList<Integer>> list"list is an ArrayList whose items are ArrayLists of Integers": a list of lists. The type inside < > says what a list holds.
= new ArrayList<>();"make a new, empty one." The empty <> copies the types from the left side.
list.add(new ArrayList<>());"add one new, empty inner list at the end." The loop does this n times: index 0 is A's list, index 1 is B's list, and so on.
list.get(from).add(to);Read it left to right: "get vertex from's list, then add to at its end."
for (int j : list.get(1))"for each number j in B's list." This is a for-each loop: no index and no i++. It visits every item in order and stops after the last one.

Why Integer and not int? The types inside < > must be classes. Integer is the class version of int, and Java converts between the two for you, so add(to) works with a plain int, and int j in the for-each loop gets a plain int back.

Notice the difference when listing B's neighbors: the matrix loop checks all n cells in row 1, while the list loop only visits B's real neighbors.

One more difference: the matrix loop always gives neighbors in index order (A, B, C, …), but an ArrayList keeps them in the order the edges were added. Here both give A C D. In the next lessons, this order matters: it decides which neighbor BFS and DFS visit first.

Your coding task: turn a matrix into a list

In , you read a matrix and wrote its adjacency list by hand: for each row, list the columns that hold a 1. Now write that in Java.

Finish toList in about 7 lines where it says YOUR CODE. You need a loop inside a loop: the outer loop picks row i, and the inner loop checks each column j of that row. To add to a vertex's list, use list.get(i).add(j), as in the adjacency list program above. Test 1 is the directed graph from Reading practice. Test 2 is the undirected graph from this part, with a vertex E that has no edges. Run it: the printed lines must match the expected lines in the comments.

 1import java.util.ArrayList;
 2
 3public class Main {
 4  static char[] names = {'A', 'B', 'C', 'D', 'E'};
 5  static int n = names.length;
 6
 7  // Builds the adjacency list of a graph from its matrix.
 8  static ArrayList<ArrayList<Integer>> toList(int[][] adj) {
 9    ArrayList<ArrayList<Integer>> list = new ArrayList<>();
10    for (int i = 0; i < n; i++) {
11      list.add(new ArrayList<>());   // one empty list each
12    }
13    // YOUR CODE:
14    // 1. Visit every cell: row i (from 0 to n - 1),
15    //    and in each row, column j (from 0 to n - 1).
16    // 2. If adj[i][j] is 1, there is an edge from i to j:
17    //    add j to vertex i's list.
18
19    return list;
20  }
21
22  // Given: prints each vertex's list, like "A: C D".
23  static void printList(ArrayList<ArrayList<Integer>> list) {
24    for (int i = 0; i < n; i++) {
25      System.out.print(names[i] + ":");
26      for (int j : list.get(i)) {
27        System.out.print(" " + names[j]);
28      }
29      System.out.println();
30    }
31  }
32
33  public static void main(String[] args) {
34    // Test 1: the directed graph from Reading practice
35    int[][] directed = {
36      {0, 0, 1, 1, 0},   // A -> C, A -> D
37      {1, 0, 0, 0, 0},   // B -> A
38      {0, 1, 0, 0, 0},   // C -> B
39      {0, 1, 0, 0, 1},   // D -> B, D -> E
40      {0, 0, 0, 0, 0}    // E points nowhere
41    };
42    printList(toList(directed));
43    // expected:
44    // A: C D
45    // B: A
46    // C: B
47    // D: B E
48    // E:
49
50    // Test 2: undirected A-B, A-D, B-C, B-D (E has no edges)
51    int[][] undirected = {
52      {0, 1, 0, 1, 0},
53      {1, 0, 1, 1, 0},
54      {0, 1, 0, 0, 0},
55      {1, 1, 0, 0, 0},
56      {0, 0, 0, 0, 0}
57    };
58    printList(toList(undirected));
59    // expected:
60    // A: B D
61    // B: A C D
62    // C: B
63    // D: A B
64    // E:
65  }
66}

▶ This program runs as is. Try it in the Programiz online compiler: tap Copy, paste it there, and press Run.

Show one possible answer
 1static ArrayList<ArrayList<Integer>> toList(int[][] adj) {
 2  ArrayList<ArrayList<Integer>> list = new ArrayList<>();
 3  for (int i = 0; i < n; i++) {
 4    list.add(new ArrayList<>());   // one empty list each
 5  }
 6  for (int i = 0; i < n; i++) {
 7    for (int j = 0; j < n; j++) {
 8      if (adj[i][j] == 1) {
 9        list.get(i).add(j);   // edge i -> j
10      }
11    }
12  }
13  return list;
14}

Output: the ten lines in the comments, from A: C D to the last E:. E's list is empty in both tests, because E's row is all 0s.

Row i is the from vertex and column j is the to vertex, so a 1 in adj[i][j] goes into i's list. And because j counts up from 0, every list comes out in alphabetical order. BFS and DFS use that order in the next lessons.

A common mistake is list.get(j).add(i), the wrong way around. Test 2 still passes: an undirected matrix is a mirror image, so every edge is stored both ways. Test 1 catches it. It prints A: B, B: C D, C: A, D: A, E: D: the arrows coming into each vertex, not going out. That is why the tests include a directed graph.

Real-life application: a mini map app

Extra topic. This goes a step beyond the lesson and is not in the self-check. Read it if you are curious how map apps find a route.

This program finds the fastest route from A to C in the . The method is called Dijkstra's algorithm (say "DIKE-struh"), named after the Dutch computer scientist Edsger Dijkstra, who came up with it in 1956. It follows four steps, the same ones you would do by hand:

  1. Start at A with a time of 0. Every other place is "not reached yet."
  2. Each round, pick the unfinished place with the smallest time so far. Its time is now final.
  3. From that place, check each road. If going through it is faster than the time written for a neighbor, write the new time and remember where you came from.
  4. When every place is done, walk back from C using "came from" to read the route.
 1public class FastestRoute {
 2  static char[] names = {'A', 'B', 'C', 'D'};
 3  static int n = names.length;
 4  static int[][] mins = new int[n][n];   // travel minutes; 0 = no road
 5  static final int INF = Integer.MAX_VALUE;   // "not reached yet"
 6
 7  // two-way road: set both cells
 8  static void addRoad(int a, int b, int minutes) {
 9    mins[a][b] = minutes;
10    mins[b][a] = minutes;
11  }
12
13  public static void main(String[] args) {
14    addRoad(0, 1, 7);    // A - B: 7 min
15    addRoad(0, 3, 4);    // A - D: 4 min
16    addRoad(1, 2, 12);   // B - C: 12 min
17    addRoad(1, 3, 5);    // B - D: 5 min
18
19    int start = 0, goal = 2;           // from A to C
20    int[] best = new int[n];           // fastest time found so far
21    int[] cameFrom = new int[n];       // the place just before it
22    boolean[] done = new boolean[n];   // time is final
23    for (int i = 0; i < n; i++) {
24      best[i] = INF;
25      cameFrom[i] = -1;
26    }
27    best[start] = 0;
28
29    for (int round = 0; round < n; round++) {
30      // 1. pick the unfinished place with the smallest time
31      int u = -1;
32      for (int i = 0; i < n; i++) {
33        if (done[i]) continue;
34        if (u == -1 || best[i] < best[u]) u = i;
35      }
36      if (best[u] == INF) break;   // the rest cannot be reached
37      done[u] = true;
38
39      // 2. try every road out of u: is going through u faster?
40      for (int v = 0; v < n; v++) {
41        if (mins[u][v] > 0 && !done[v]) {
42          int t = best[u] + mins[u][v];
43          if (t < best[v]) {
44            best[v] = t;
45            cameFrom[v] = u;
46          }
47        }
48      }
49    }
50
51    // 3. walk back from the goal to build the route
52    String route = "" + names[goal];
53    for (int v = cameFrom[goal]; v != -1; v = cameFrom[v]) {
54      route = names[v] + " -> " + route;
55    }
56    System.out.println("Fastest route: " + route);
57    System.out.println("Time: " + best[goal] + " minutes");
58    // prints: Fastest route: A -> B -> C
59    //         Time: 19 minutes
60  }
61}

▶ Try it in the Programiz online compiler: tap Copy, paste it there, change public class FastestRoute to public class Main (Programiz saves your code as Main.java, and Java needs the file name and the public class name to match), then press Run.

Here is how to read the new lines aloud:

CodeRead it as
Integer.MAX_VALUE"the biggest number an int can hold." We use it to mean "not reached yet": any real time is smaller.
boolean[] done"done is an array of true/false values." done[i] becomes true once place i's time is final. It starts all false.
if (done[i]) continue;"if place i is done, skip it and go to the next i."
if (t < best[v])"if going through u is faster than v's best time so far": then update v's time and write that v came from u.
v = cameFrom[v]"step back to the place before v." The walk stops at A, whose cameFrom is -1.

The table below traces the program round by round, so you can check each step:

RoundPicked (smallest time)Roads checkedWhat changes
1A (0 min)A–B: 0 + 7 = 7
A–D: 0 + 4 = 4
B = 7 (from A), D = 4 (from A)
2D (4 min)D–B: 4 + 5 = 99 is not faster than 7, so B stays 7
3B (7 min)B–C: 7 + 12 = 19C = 19 (from B)
4C (19 min)no unfinished neighborsall done

Walking back: C came from B, and B came from A. So the route is A → B → C, 19 minutes, the same answer as in Part 2.

Why is the picked time final? Every other unfinished place already takes longer to reach, and travel times are never negative, so no detour through them can be faster. (This is also why Dijkstra's algorithm does not work if a weight can be negative.)

Real map apps have millions of places, so they use faster versions of this idea, with shortcuts worked out ahead of time. The core question is the same: which path has the smallest total weight?

Part 9 · Check yourself

Self-check

Not graded. Tap an answer to see if you got it, and read why.

  1. A graph is made of:

  2. Which statement is true?

  3. In an undirected graph, the adjacency matrix is always:

  4. A graph has 6 vertices. How many cells does its adjacency matrix have?

  5. Your graph has 1,000 vertices, and each one connects to only about 3 others. Which representation saves more memory?

  6. In a weighted graph, what does the adjacency matrix store?

Score: 0 / 6

Key takeaways

  1. A graph is a set of vertices and edges. Trees are a special kind of graph.
  2. Directed edges are arrows (one way). Weighted edges carry numbers.
  3. Adjacency matrix: [row][column] = 1 means an edge from row to column. Undirected → symmetric. Diagonal → loops.
  4. Adjacency list: each vertex has a list of where its edges go, ending in null.
  5. Matrix: quick edge checks, but lots of memory. List: saves memory for sparse graphs.

Next lesson: Breadth-first search (BFS), a way to visit every vertex of a graph, level by level.

References

  1. A. Bhargava, Grokking Algorithms. Manning, 2016, Chapter 6 (introduction to graphs).
  2. T. H. Cormen, C. E. Leiserson, R. L. Rivest, and C. Stein, Introduction to Algorithms, 4th ed. MIT Press, 2022, Section 20.1 (Representations of graphs).
  3. Programiz, "Graph Data Structure," "Adjacency Matrix," and "Adjacency List." programiz.com/dsa/graph