We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Adjacency List

In the first assignment, we created a graph using an adjacency matrix:

0 1 2 3 4
0 False True False False True
1 True False True True True
2 False True False True False
3 False True True False True
4 True True False True False

Through the rest of this course, we'll primarily be using an adjacency list instead. An adjacency list stores a list of vertices for each vertex that indicates where the connections are:

0 connects with 1 4
1 connects with 0 2 3 4
2 connects with 1 3
3 connects with 1 2 4
4 connects with 0 1 3

Assignment

Let's rebuild our Graph class using an adjacency list.

    • It should create an empty dictionary called graph as a data member.
    • Be sure to map both vertices to each other, it's a bidirectional edge.
    • Handle the case where a set for a vertex doesn't exist yet.
    • The resulting graph maps vertices to a set of all other vertices they share an edge with. For example:
result = {0: {1, 4}, 1: {0, 2, 3, 4}, 2: {1, 3}, 3: {1, 2, 4}, 4: {0, 1, 3}}