Profile

Unblock all features

Sign in to track progress and visualise your code.

ntree.ai
Linked lists, trees and graphs

Graph

A graph is a data structure that consists of nodes, where each node has a value and links to other nodes, called edges.

Compared to a tree, there is no root, and the edges can form cycles, so a node can be reached in more than one way.

7
3
9
4
8

Graph representation

A graph can be represented in different ways apart from creating an object for each node. Every example below shows the same graph.

Adjacency list

An adjacency list stores one list per node, holding every node it has an edge to. It takes O(V+E)O(V + E) space, where VV is the number of nodes and EE is the number of edges.

This representation is most common in problems.

7
3
9
4
8
7
3
9
3
7
4
9
7
4
4
3
9
8
8
4

Edge list

An edge list is a list of node pairs, one per edge.

Problems usually give a graph this way, and the first step of a solution is often to turn it into an adjacency list.

7
3
9
4
8
73
79
34
94
48

Adjacency matrix

An adjacency matrix is a V × V grid where matrix[u][v] is 1 when there is an edge between u and v, and 0 otherwise.

7
3
9
4
8
7 3 9 4 8 7
0
1
1
0
0
3
1
0
0
1
0
9
1
0
0
1
0
4
0
1
1
0
1
8
0
0
0
1
0

Graph traversal

Depth first search (DFS)

DFS goes as deep as it can along one neighbour before it moves on to the next one.

Unlike a tree, a graph can have cycles, so we need to keep track of visited nodes, otherwise we would traverse the graph forever.

7
3
9
4
8
visit 7
1 / 11
Depth first search
Python
def dfs(graph: dict[int, list[int]], start: int) -> list[int]:
# Return the nodes with depth first search traversal
# graph is an adjacency list where graph[node] lists the neighbours of node
return []
graph = {7: [3, 9], 3: [7, 4], 9: [7, 4], 4: [3, 9, 8], 8: [4]}
print(dfs(graph, 7))

Breadth first search (BFS)

BFS visits the graph level by level: first the start node, then every node one edge away from it, then every node two edges away, and so on.

It adds each node's neighbours that are not visited yet to a queue, and visits the nodes from it in order, so a level is finished before the next one starts.

7
3
9
4
8
7
visit 7
1 / 6
Breadth first search
Python
def bfs(graph: dict[int, list[int]], start: int) -> list[int]:
# Return the nodes with breadth first search traversal
# graph is an adjacency list where graph[node] lists the neighbours of node
return []
graph = {7: [3, 9], 3: [7, 4], 9: [7, 4], 4: [3, 9, 8], 8: [4]}
print(bfs(graph, 7))
Was this lesson helpful?