Notes

Search

Search IconIcon to open search

BFS and Graph Algorithm Implementations

Last updated Dec 31, 2022

So far, we have seen a few graph traversals;

BFS order is analogous to level order traversal.

Typical BFS Implementation

The typical BFS implementation is non-recursive.

The queue data structure is going to enforce the idea that we need to traverse in the order of distance from the source.

An invariant of BFS is that distance to all items on queue is always $k$ or $k+1$ for some $k$.

Graph API 1: Integer Vertices

Common convention: Number nodes irrespective of “label”, and use number throughout the graph implementation. Map<Label, Integer>.

Graph API 2: Princeton Graph API

1
2
3
4
5
6
7
public class Graph {
    public Graph(int V);
    public void addEdge(int v, int w);
    Iterable<Integer> adj(int v);
    int V();
    int E();
...

Graph Representations

Adjacency Matrix

0123456789
0
1
2
3
4
5
6
7
8
9

Takes $O(V^2)$ time complexity.

Adjacency List

Maintain an array of lists indexed by vertex. This is the most popular representation. This is because graphs are often sparse (not many edges in each bucket).