Basic Algorithms of Graph
Basic Algorithms of Graph
Waris Ali
Graphs
Definition = a set of nodes (vertices) with
edges (links) between them.
G = (V, E) - graph 1 2
V = set of vertices V = n
E = set of edges E = m 3 4
Binary relation on V
Subset of V x V ={(u,v): u V, v V}
2
Graph Representation
Adjacency matrix representation of G = (V, E)
Assume vertices are numbered 1, 2, … V
The representation consists of a matrix A V x V :
aij = 1 if (i, j) E
0 otherwise
1 2 3 4 5
1 0 1 0 0 1 For undirected
1 2
2 1 0 1 1 1 graphs, matrix A
3
3 0 1 0 1 0 is symmetric:
5 4 4 0 1 1 0 1 aij = aji
3
Undirected graph 5 1 1 0 1 0 A = AT
Graph Representation
Adjacency list representation of G = (V, E)
An array of V lists, one for each vertex in V
Each list Adj[u] contains all the vertices v that are
adjacent to u (i.e., there is an edge from u to v)
Can be used for both directed and undirected
graphs
1 2 1 2 5 /
3 2 1 5 3 4 /
3 2 4
5 4
4 2 5 3 /
Undirected graph 5 4 1 2
4
Degree of a Vertex
G=(V,E) is an undirected graph
the degree of a vertex v is no, of edges
incident on it
G=(V,E) is a directed graph
the out degree of a vertex v is no. of out
going edges from a vertex
the in degree of a vertex v is no. of in coming
edges on a vertex
5
Degree of a Vertex
Adjacency matrix
Deg_Ver(A[][], |V|, i)
deg=0; O(V) complexity
for (j=1; j<=|V|; j++)
deg=deg+A[i][j]; 1 2 3 4 5
1 0 0 0 0 1
2 0 0 1 1 0
3 0 1 0 1 0
4 0 1 1 0 1
6
5 1 0 0 1 0
Degree of a Vertex (directed
Graph)
deg_Ver(A[][], |V|, i)
indeg=0;
Outdeg=0; O(V) complexity
for (j=1; j<=|V|; j++)
outdeg=outdeg+A[i][j];
1 2 3 4 5
1 0 1 0 0 1
for (j=1; j<=|V|; j++)
2 0 0 0 1 1
indeg=indeg+A[j][i];
3 0 1 0 0 0
4 0 1 1 0 1
7
5 0 0 0 1 0
Degree of a Graph
G=(V,E) is a graph
the degree of graph G is equal to sum of
degress of all the vertices
1 2 3 4 5
1 0 0 0 0 1
2 0 0 1 1 0
3 0 1 0 1 0
4 0 1 1 0 1
5 1 0 0 1 0
8
Degree of a Graph
Deg_Ver(A[][], |V|, i)
deg=0;
for (i=0; i<=|V|; i++) O(V2) complexity
for (j=1; j<=|V|; j++)
deg=deg+A[i][j];
1 2 3 4 5
1 0 0 0 0 1
2 0 0 1 1 0
3 0 1 0 1 0
4 0 1 1 0 1
9
5 1 0 0 1 0
Graph Type
(Directed vs Undirected)
Graph_Type(A[][], |V|)
for (i=1; i<=|V|; i++)
O(V2) complexity
for(j=i+1; j<=|V|; j++) 2 4 5
1 3
if(A[i][j] != A[j][i]) { 0 1 0 0 1
1
return false 2 0 0 0 1 1
} 3 0 1 0 0 0
return true; 4 0 1 1 0 1
5 0 0 0 1 0
10
Graph Type
(Simple vs Multi)
Graph_Type(A[][], |V|)
for (i=1; i<=|V|; i++)
O(V2) complexity
for(j=1; j<=|V|; j++) 2 4 5
1 3
if(A[i][j] >1) { 0 1 0 0 1
1
return false 2 0 0 0 1 1
} 3 0 1 0 0 0
return true; 4 0 1 1 0 1
5 0 0 0 1 0
11
Graph Type
(Pesudo)
Graph_Type(A[][], |V|)
for (i=1; i<=|V|; i++) O(V) complexity
if(A[i][i] != 0) { 1 2 3 4 5
return false 1 0 1 0 0 1
} 2 0 0 0 1 1
return true; 3 0 1 0 0 0
4 0 1 1 0 1
5 0 0 0 1 0
12