Graphs - Java
Graphs - Java
(JAVA)
Hira Awais
Lecturer (DCS)
DDSA (FOC)
Slide courtesy: Dr. Zahid Halim
Graph Definition
A graph G is denoted by G = (V, E) where
V is the set of vertices or nodes of the graph
E is the set of edges or arcs connecting the vertices in V
Each edge E is denoted as a pair (v,w) where v,w e V
For example in the graph below
1 V = {1, 2, 3, 4, 5, 6}
3
E = {(1, 2) (2, 5) (3, 6) (4, 6) (5, 6)}
This is an example of an unordered or
undirected graph
6 4
5
Graph Definition
If the pair of vertices is ordered then the graph is a directed
graph or a di-graph
2
1 3 Here,
V = {1, 2, 3, 4, 5, 6}
E = {(1, 2) (2, 5) (5, 6) (6, 3) (6, 4)}
6 4
Weakly Connected
Applications of Graphs
Driving Map
Edge = Road
Vertex = Intersection
Edge weight = Time required to cover the road
Airline Traffic
Vertex = Cities serviced by the airline
Edge = Flight exists between two cities
Edge weight = Flight time or flight cost or both
Computer networks
Vertex = Server nodes
Edge = Data link
Edge weight = Connection speed
CAD/VLSI
Representing Graphs: Adjacency Matrix
Adjacency Matrix
Two dimensional matrix of size n x n where n is the number of vertices in the graph
a[i, j] = 0 if there is no edge between vertices i and j
a[i, j] = 1 if there is an edge between vertices i and j
Undirected graphs have both a[i, j] and a[j, i] = 1 if there is an edge between vertices i
and j
a[i, j] = weight for weighted graphs
1 2 5
3
3
4
6 4 5 6
6
5 3 4
An adjacency list for a weighted graph should contain two elements in the list nodes
– one element for the vertex and the second element for the weight of that edge