algoritmauzmanı
Sign in
TREN
8.2Graph with Adjacency Lists
Lesson 8.2.4

Breadth-first search (BFS)

This lesson is the twin of BFS with a matrix. The algorithm is the same: a queue, a visited array and marking a vertex as it joins the queue. The only change is how the neighbours are found. With a matrix all n cells of the row of u were checked; with an only the list of u is walked.

What you will learn
  • How walking a list replaces scanning a row in BFS
  • Why BFS with lists takes O(n + e) time
  • How the order of the neighbours decides the output
8 minTime O(n + e)Memory O(n)C · Java · Python

1The idea

marks the start vertex and puts it into the . On each turn the front vertex u leaves and is printed. Then the list of u is walked with the loop from the printing neighbours lesson: if the v in a node is not marked, it is marked and added to the back of the queue. The matrix test adj[u][v] == 1 is not needed, because the list holds only neighbours.

The output is the same as with the matrix: 0 1 3 2 4 5. That is because the lists are kept sorted from smallest to largest (insertSorted from the adding edges lesson). Had the edges been added to the front of the lists, the neighbours would be walked in reverse and the output would be 0 3 1 4 2 5. Both are correct BFS orders; the distance layers stay the same, only the order inside a layer changes.

Why did the time change? Every vertex leaves the queue once, and when it does its list is walked once. In an undirected graph each edge sits in two lists, so the lists add up to 2e nodes. The total work is n + 2e, that is O(n + e). With the matrix it was n × n.

GraphMatrix (n²)Lists (n + 2e)
Sample: n = 6, e = 73620
n = 1000, e = 30001,000,0007000
Complete graph: n = 6, e = 153636

2Step by step

The drawing walks the sample graph with BFS starting at 0. Faded vertices have not been found yet; u is the vertex just taken out of the queue, and on the right its list being walked (orange). The green ones were printed earlier. Orange edges are the ones through which a new vertex was found. The queue is shown under the drawing.

adjNULLNULLNULLNULLNULLNULL012345012345?0?1?2?3?4?51?3?0?2?4?1?5?0?4?1?3?5?2?4?u
Queue (front on the left)
  1. Start: no vertex is marked. bfs(&g, 0) is called.
  2. 0 is marked and put into the queue. Queue: 0.
  3. 0 leaves and is printed. Its list is 1, 3; both are marked and join the queue. Only 2 nodes were looked at. Output: 0.
  4. 1 leaves and is printed. Its list is 0, 2, 4. 0 is marked; 2 and 4 join the queue. Output: 0 1.
  5. 3 leaves and is printed. The 0 and 4 in its list are already marked. Output: 0 1 3.
  6. 2 leaves and is printed. The 5 in its list is seen for the first time and joins the queue. Output: 0 1 3 2.
  7. 4 leaves and is printed. The 1, 3 and 5 in its list are marked. Output: 0 1 3 2 4.
  8. 5 leaves and is printed. The queue is empty and the loop ends. Output: 0 1 3 2 4 5.
  9. The result is the same as with the matrix. This time 14 list nodes were looked at in all, instead of 36 cells.

#define MAX 8 struct Node {    int data;    struct Node* next;}; struct Graph {    int n;    bool directed;    struct Node* adj[MAX];}; void bfs(struct Graph* g, int start) {    bool visited[MAX] = {false};    int queue[MAX];    int front = 0, rear = 0;    visited[start] = true;          // mark it as it joins the queue    queue[rear++] = start;    while (front < rear) {        int u = queue[front++];     // take the front one        printf("%d ", u);        for (struct Node* temp = g->adj[u]; temp != NULL; temp = temp->next) {            int v = temp->data;     // the list holds only neighbours            if (!visited[v]) {                visited[v] = true;                queue[rear++] = v;  // the neighbour goes to the back            }        }    }}
class Node {    int data;    Node next;    Node(int data) { this.data = data; }} class ListGraph {    int n;    boolean directed;    Node[] adj;     ListGraph(int n, boolean directed) {        this.n = n;        this.directed = directed;        adj = new Node[n];    }     void bfs(int start) {        boolean[] visited = new boolean[n];        java.util.ArrayDeque<Integer> queue = new java.util.ArrayDeque<>();        visited[start] = true;          // mark it as it joins the queue        queue.add(start);        while (!queue.isEmpty()) {            int u = queue.poll();       // take the front one            System.out.print(u + " ");            for (Node temp = adj[u]; temp != null; temp = temp.next) {                int v = temp.data;      // the list holds only neighbours                if (!visited[v]) {                    visited[v] = true;                    queue.add(v);       // the neighbour goes to the back                }            }        }    }}
from collections import deque class Node:    def __init__(self, data):        self.data = data        self.next = None class ListGraph:    def __init__(self, n, directed=False):        self.n = n        self.directed = directed        self.adj = [None] * n     def bfs(self, start):        visited = [False] * self.n        visited[start] = True           # mark it as it joins the queue        queue = deque([start])        while queue:            u = queue.popleft()         # take the front one            print(u, end=" ")            temp = self.adj[u]            while temp is not None:                v = temp.data           # the list holds only neighbours                if not visited[v]:                    visited[v] = True                    queue.append(v)     # the neighbour goes to the back                temp = temp.next

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n + e)

Every vertex leaves the queue once (n) and its list is walked once; the lists add up to 2e nodes.

Memory
O(n)

The visited array and the queue hold at most n elements.

On a sparse graph (e far below n²) lists make a big difference. In a complete graph e is about n²/2 and both structures end up at the same order.

4Common mistake

A common mistake when moving the matrix code to lists is keeping the loop over vertex numbers:

for (int v = 0; v < g->n; v++)    if (hasEdge(g, u, v) && !visited[v]) {        visited[v] = true;        queue[rear++] = v;    }

The output is right, but hasEdge walks the list from the start on every call. Walking a list n times for each vertex is slower than the matrix. The gain of lists is that the loop passes only through the nodes in the list; the neighbours are read straight from it.

5Try it

If the edges had been added to the front of the lists (lists from largest to smallest), what would BFS from 0 give on the sample graph?

Show the answer

The answer is A. The list of 0 becomes 3, 1: 3 then 1 join the queue. When 3 leaves, 4 is added; when 1 leaves, 2 is added. When 4 leaves, 5 is added. Order: 0 3 1 4 2 5.

Roughly how many steps does BFS with lists take on an undirected graph with 100 vertices and 150 edges?

Show the answer

The answer is A. n + 2e = 100 + 300 = 400. With a matrix, n² = 10,000 cells would be checked.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.