8 Graph
8 Graph
Representations of Graphs
•Adjacency Matrices
•Adjacency Lists
Adjacency Matrices
Graphs G = (V, E) can be represented by adjacency matrices
G[v1..v|V |, v1..v|V |], where the rows and columns are indexed by the nodes,
and the entries G[vi, vj] represent the edges. In the case of unlabeled
graphs, the entries are just boolean values.
A B C D
A 0 1 1 1
B
C
1
1
0
0
0
0
1
1
D 1 1 1 0
Adjacency Matrices
In case of labeled graphs, the labels themselves may be introduced into
the entries.
A B C D
A 10 4 1
B 15
C 9
D
Adjacency matrices require O(|V |2) space, and so they are space-efficient only when
they are dense (that is, when the graphs have many edges). Time-wise, the adjacency
matrices allow easy addition and deletion of edges.
Adjacency Lists
A representation of the graph consisting of a list of nodes, with each
node containing a list of its neighboring nodes.
•Depth-First Traversal
•Breadth-First Traversal
Depth-First Traversal
• algorithm dft(x)
visit(x)
FOR each y such that (x,y) is an edge DO
IF <y was not visited yet >
THEN dft(y)
Depth-First Traversal
Breadth-First Traversal
visit(start node)
queue <- start node
WHILE queue is not empty DO
x <- queue
FOR each y such that (x,y) is an edge
and y has not been visited yet DO
visit(y)
queue <- y
END
END
Breadth-First Traversal
Breadth-First Traversal
Breadth-First Traversal
Breadth-First Traversal
• Each vertex is clearly
• marked at most once,
• added to the list at most once (since that happens only when it's
marked), and
• removed from the list at most once.
Since the time to process a vertex is proportional to the length of its
adjacency list, the total time for the whole algorithm is O(m).
• The traversal goes a level at a time, left to right within a level (where a
level is defined simply in terms of distance from the root of the tree).
Breadth-First Traversal
• Every edge of G can be classified into one of three groups.
• Some edges are in T themselves.
• Some connect two vertices at the same level of T.
• The remaining ones connect two vertices on two adjacent levels. It
is not possible for an edge to skip a level.
• Breadth-first search tree really is a shortest path tree starting from
its root.
Relation between BFS and DFS
bfs(G) dfs(G)
{ {
list L = empty tree list L = empty
T = empty tree T = empty
choose a starting vertex x choose a starting vertex x
search(x) search(x)
while(L nonempty) while(L nonempty)
remove edge (v,w) from start of L remove edge (v,w) from end of L
if w not yet visited if w not yet visited
{ {
add (v,w) to T add (v,w) to T
search(w) search(w)
} }
} }
search(vertex v) {
visit(v);
for each edge (v,w)
add edge (v,w) to end of L
}
Relation between BFS and DFS