Introduction
Imagine you want to keep track of connections between places or friends. Choosing the right way to store these connections can make finding and using them much easier and faster.
Think of a city map where every street intersection is a node. An adjacency matrix is like a big table listing every possible pair of intersections and marking if a direct road connects them. An adjacency list is like having a list at each intersection showing only the streets that lead out from there.
Nodes
0 1 2 3
0 [0] [1] [0] [0]
1 [1] [0] [1] [1]
2 [0] [1] [0] [0]
3 [0] [1] [0] [0]
Adjacency List:
0: 1
1: 0, 2, 3
2: 1
3: 1graph_matrix = [
[0, 1, 0, 0],
[1, 0, 1, 1],
[0, 1, 0, 0],
[0, 1, 0, 0]
]
graph_list = {
0: [1],
1: [0, 2, 3],
2: [1],
3: [1]
}
# Check if node 0 is connected to node 1 using matrix
print('Matrix:', graph_matrix[0][1] == 1)
# Check if node 0 is connected to node 1 using list
print('List:', 1 in graph_list[0])