Unit 5 Graphs
Unit 5 Graphs
Level 3
UNIT 5
GRAPHS AND TREES
What is a graph?
A data structure that consists of a set of nodes
(vertices) and a set of edges that relate the nodes to
each other
The set of edges describes relationships among the
vertices
Formal definition of graphs
2
O( N )
Graph terminology (cont.)
What is the number of edges in a complete
undirected graph with N vertices?
N * (N-1) / 2
2
O( N )
Graph terminologies (cont.)
Weighted graph: a graph in which each edge
carries a value
Graph implementation
1. Array-based implementation
◦ A 1D array is used to represent the vertices
◦ A 2D array (adjacency matrix) is used to represent
the edges [Implement the following graph into an
array-based]
Array-based implementation
A Graph and its adjacency Matrix
Q: Implement the following graph into
adjacency matrix
Graph implementation (cont.)
2. Linked-list implementation
Q: Implement the following graph into a linked list
◦ A 1D array is used to represent the vertices
◦ A list is used for each vertex v which contains the
vertices which are adjacent from v (adjacency list)
Linked-list implementation
A graph and its Adjacency List
Q:Implement the following graph into adjacency
list
Adjacency matrix vs. adjacency list
representation
Adjacency matrix
◦ Good for dense graphs
◦ Memory requirements: O(|V| + |E| ) = O(|V|
2
)
◦ Connectivity between two vertices can be
tested quickly
Adjacency list
◦ Good for sparse graphs
◦ Memory requirements: O(|V| + |E|)=O(|V|)
◦ Vertices adjacent to another vertex can be
found quickly
Degree of the Graph
G:Given the following graph, write the degree of
each vertix