View on GitHub

csc263

Notes for CSC263 - Data Structures and Analysis

Back to index

Breadth-First Search

Graphs

Types of graphs

Representing graphs

Adjacency lists

Adjacency matrices

Breadth First Search

def BFS(G, s):
    colour[s] = "grey"
    d[s] = 0
    p[s] = NIL
    for each v in V-{s}:
        colour[v] = "white"
        d[v] = infinity
        p[v] = NIL
    Q = EmptyQueue()
    "..."

Time complexity

BFS is $\mathcal O(\vert V\vert + \vert E\vert )$ since each node needs to be discovered, and for each node every edge needs to be checked

Discovery path

Let $\delta(s, v)$ be the minimum distance between $s$ and $v$

Lemma 1. If $u$ is added to the queue $Q$ before $v$, is then $d[u] \leq d[v]$

Suppose for contradiction that $u, v$ is the first pair of vertices where $v$ comes after $u$ and $d[u] > d[v]$.

Theorem. After BFS(G, s), for every $v \in V$, $d[v] = \delta(s, v)$. Thus, BFS finds shortest paths.

Suppose there exists $x \in V$ so that $d[x] \neq \delta(s, x)$ (clearly $x \neq s$).