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.
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 space, where is the number of nodes and is the number of edges.
This representation is most common in problems.
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.
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.
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.
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.