Graphs (representation)
Computer Science · Data structures
Question 1 of 10
0In Graph 2, what is the out-degree of vertex A?
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Graphs (representation) explained
A graph is a set of nodes, also called vertices, joined by edges. Graphs model networks such as road maps, social networks and the links between web pages. To process a graph, a program must store it in a data structure, and the two common choices are an adjacency matrix and an adjacency list.
An adjacency matrix is a square grid with one row and one column for each node. The entry in row and column is 1 if there is an edge between node and node , and 0 otherwise. For a graph with nodes the matrix has entries, which is wasteful when the graph has few edges. Checking whether two nodes are joined takes a single lookup.
An adjacency list stores, for each node, a list of the nodes it is joined to. It uses less memory for graphs with few edges. In an undirected graph with edges, the lists hold entries in total, because each edge appears in the list of both of its ends.
A common mistake is to record an undirected edge only once. It must appear in both directions, in either representation, or the graph will look different from the way it was drawn.
Worked example
A graph has four nodes, A, B, C and D, and five undirected edges: A-B, A-C, B-C, B-D and C-D.
- The adjacency matrix has entries.
- The adjacency list has entries, one for each end of each edge.
- Node B is joined to A, C and D, so row B of the matrix has three 1s and the list for B has three entries.
What you will practise
41 diagrams. Type the label for each part and get instant feedback.
Example questions
- In Graph 1, how many vertices are there?
- In Graph 1, how many edges (lines) are there?
- What is the degree of vertex F in Graph 1?
- In Graph 2, what is the out-degree of vertex A?
- Which vertex in Graph 2 has no outgoing edges?
- What is the name of the part numbered 1 in Graph 4?
- What is the name of the part numbered 2 in Graph 4?
- What name is given to the part numbered 3 in Graph 4, an edge that starts and ends at the same vertex?
…and 33 more.