Graphs
Graphs
What is a graph?
• A graph is a data structure for representing connections among items,
and consists of vertices connected by edges
19 9
A B C
14
8 16 10
11 17 E
G F D 18
12 14
Graphs: Prims Algorithm
Find the minimum spanning tree (MST) of the following graph
starting from vertex A.
9
A B C
14
8 10
11 E
G F D
12
Graphs: Kruskal’s Algorithm
Kruskal’s algorithm nds the minimum spanning tree (MST) of a
graph.
Kruskal’s algorthim rst lists out all of the edges from least to
greatest (in terms of their weights). It then chooses the edge with
the smallest weight which doesn’t form a cycle. It repeats this
until all vertices have been visited.
fi
fi
Graphs: Kruskal’s Algorithm
Find the minimum spanning tree (MST) of the following graph
using Kruskal’s algorithm.
8 B 5
A C
3 4
H 7
E 8
12
3 2
G D
F
10 10
Graphs: Kruskal’s Algorithm
Find the minimum spanning tree (MST) of the following graph
using Kruskal’s algorithm.
8 B 5
A C
3
H
E 8
3 2
G D
F
10
Graphs: Dijkstra’s Algorithm
Find the shortest path tree from vertex A
3 7
D E F
2 3
5 1 7
C B A
2 2
12
Graphs: Dijkstra’s Algorithm
Find the shortest path tree from vertex A
A B C D E F
3 0 ∞ ∞ ∞ ∞ ∞
D E F
2 12 ∞ ∞ 7
3
1 4 ∞ 3 5
4 6 5
C B A
2 2 6 5
6
Graph Implementations:
There are two main ways in which graphs are implemented:
1 1 0 1 0 1
2 3
1 1 0 0 0
4
1 0 0 0 1
0 1 0 1 0
Adjacency List
0
1 2 3 NULL
1 0 2 4 NULL
2 3
0 1 NULL
4
0 4 NULL
1 3 NULL
Graphs: Breadth-first-search (BFS)