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:

01234
0FalseTrueFalseFalseTrue
1TrueFalseTrueTrueTrue
2FalseTrueFalseTrueFalse
3FalseTrueTrueFalseTrue
4TrueTrueFalseTrueFalse

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:

0connects with14
1connects with0234
2connects with13
3connects with124
4connects with013

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}}