Breadth First Search

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Graph Algorithms: Introduction

Basic terminology:
I Graph G = (V, E)
V = set of vertices {vi }
E = set of edges = a subset of V V = {(vi , vj )}
I |E| = O(|V |2 )
If G is connected, then |E| |V | 1.
I Some variants
I undirected: edge (u, v) = (v, u)
I directed: (u, v) is edge from u to v, u v.
I weighted: weight on either edge or vertex
I multigraph: multiple edges between vertices

I Further reading: Appendix B.4, pp.1168-1172.


Graph Algorithms: Introduction
Graph representation 1 by Adjacency matrix
I A = (aij ) is a |V | |V | matrix, where

1, if (i, j) E
aij =
0, otherwise

I Example
I If G is undirected, A is symmetric.
Graph Algorithms: Introduction
Graph representation 2 by Incidence matrix
I B = (bij ) is a |V | |E| matrix, where

1, if edge j enters vertex i
bij = 1, if edge j leaves vertex i
0, otherwise

I Example
Graph Algorithms: Introduction
Graph representation 3 by Adjacency list
I For each vertex v, keep list
Adj[v] = { vertices adjacent to v }
I Example
Breadth-First Search (BFS) algorithm
I the archetype for many important graph algorithms
I Input: Given G = (V, E) and a source vertex s,
Output: d[v] = distance from the source s to v for all v V .
I Distance = fewest number of edges = shortest path
I BFS idea: discovers all vertices at distance k from source vertex before
discovering any vertices at distance k + 1
Review: queue and stack data structure
I Queues and stacks are dynamic sets in which the elements removed
from the set by the delete operation is prescribed.
I The queue implements a First-In-First-Out (FIFO) policy.
The stack implements a Last-In-First-Out (LIFO) policy.
I Queue supports the following operations:
Enqueue(Q,v): insert element v into the queue Q
Dequeue(Q,v): delete element v from the queue Q
I There are several way efficient ways to implement queues and stacks
In section 10.1 of the textbook, it describes a way how to use a simple
array to implement each.
Breadth-First Search (BFS) algorithm
BFS(G,s)
// Breadth-First Search
for each vertex u in V-{s}
d[u] = +infty
endfor
d[s] = 0
Q = empty // create FIFO queue
Enqueue(Q, s)
while Q not empty
u = Dequeue(Q)
for each v in Adj[u]
if d[v] = +infty,
d[v] = d[u] + 1
Enqueue(Q, v)
endif
endfor
endwhile
return d
Breadth-First Search (BFS) algorithm
I Running time: O(|V | + |E|)
O(|V |): because every vertex enqueued at most once
O(|E|): because every vertex dequeued at most once and we examine
(u, v) only when u is dequeued at most once if directed, at most twice
if undirected.
Not (|V | + |E|)
I Correctness of BFS
shortest path proof see pp.597-600.
similar with weighted edges Dijkstras algorithm more later.

You might also like