Lec 9 - Graph Algorithms
Lec 9 - Graph Algorithms
Tree
Array
Linked List
Graph
Stack Queue
V = { A,B,C,D } V = { 1, 3,5,7,9,11}
E = {(A,B), (A,D), (B,D), (B,C)} E = {(1,3) (3,1) (11,1) (9,11) (9,9) (5,9) (5,7) }
8
1 2
6 Weighted Directed Graph
10 3
5 7
3 4 5
6
Graphs - Definitions
▪ A connected graph has a path between each pair of distinct vertices.
outdeg(2)=2
deg(1) = 2 indeg(2)=2
deg(2) = 3
deg(5) = 3 outdeg(3)=1
indeg(3)=4
Ex:
• 3 is adjacent to 1 ➔ (1,3)
From Edge (B,D) • 1 is adjacent to 3 ➔ (3,1)
. B is adjacent to D • 1 is adjacent to 11➔(11,1)
. D is adjacent to B.
3 4 5
3 4 5
12
Graph Representations
You can choose between two standard ways to represent a graph G = (V, E) :
1. Adjacency lists.
2. Adjacency matrix.
Undirected graph
For weighted graph: Weights are stored in adjacency lists Weights are stored instead of 1 and 0
For weighted graph: Weights are stored in adjacency lists Weights are stored instead of 1 and 0
▪ Given a graph G =(V, E) and a distinguished source vertex s , BFS systematically explores
the edges of G to discover every vertex that is reachable from s.
O(V + E)
➢ Print-path(G,s,x) S R W X T 2 R
➢ Print-path(G,s,w) S R W Y 2 U
➢ Print-path(G,s,r) S R X 3 W
➢ Print-path(G,s,s) Z 3 W
S
▪ This process continues until all vertices that are reachable from
the original source vertex have been discovered.
▪ If any undiscovered vertices remain, then depth-ûrst search
selects one of them as a new source, repeating the search from
that source.
a
a
Example (DFS)
Show how depth-first search works on the following graph, starting from vertex a.
c
a
a,c
Example (DFS)
Show how depth-first search works on the following graph, starting from vertex a.
d
c
a
a,c,d
Example (DFS)
Show how depth-first search works on the following graph, starting from vertex a.
c
Back edge
a
a,c,d
Example (DFS)
Show how depth-first search works on the following graph, starting from vertex a.
f
c
a
a,c,d,f
Example (DFS)
Show how depth-first search works on the following graph, starting from vertex a.
b
f
c
a
a,c,d,f,b
Example (DFS)
Show how depth-first search works on the following graph, starting from vertex a.
e
b
f
c
a
a,c,d,f,b,e
Example (DFS)
Show how depth-first search works on the following graph, starting from vertex a.
b
f
c
a
a,c,d,f,b,e
Example (DFS)
Show how depth-first search works on the following graph, starting from vertex a.
f
c
a
a,c,d,f,b,e
Example (DFS)
Show how depth-first search works on the following graph, starting from vertex a.
c
a
a,c,d,f,b,e
Example (DFS)
Show how depth-first search works on the following graph, starting from vertex a.
a
a,c,d,f,b,e
Example (DFS)
Show how depth-first search works on the following graph, starting from vertex a.
a,c,d,f,b,e
Questions