Lecture No. 7 Graphs Algorithms
Lecture No. 7 Graphs Algorithms
Graph Representations
-Matrix Representation
-Linked list Representation
Graph Traversal
-Breath First Search (BFS)
-BFS Analysis
-Depth First Search (DFS)
-DFS Analysis
Spanning Trees
- Kruskal’s algorithm and analysis
- Prim’s algorithm
The number of vertices and edges in the graph is given by the set cardinalities of the sets
V, G . In the example, |V| = 5 ,|E| =25
A graph which has all the edges is referred to as complete. An undirected complete graph ,
with n vertices, has n(n-1)/2 edges. Its space complexity is O(n2) . Such a graph is called
dense. By contrast, a graph with space complexity O(n lg n) is called sparse.
The directed graph is often referred to digraph or network. Figure shows an example of
directed graph
A complete directed graph with n vertices has n2 edges, including edges associated with
all individual vertices. If individual edges are excluded, the total number of edges is n(n-1)
Weighted graphs have several real life applications, such as air routes, computer
networks, road links
(a)Path length of 2
A path that originates and terminates at the same vertex, and links two or more vertices,
is called cycle. In the picture of the cyclic graph the path v2,v3, v4, v2 is cycle.
If a graph contains a cycle it is called cyclic. By contrast, a graph which contains no
cycles is known as acyclic.
loop
cycle
v3 v5 v7 v10 v15
v4 v9 v13
v1 v3 v5 v6
v1 v3 v5 v6
v9 v8 v7
v9 v8 v7
The cliques represent robust subnets in a network. If a path in a clique is disrupted, the
network continues to function.
v2
V1 w2 V2
v3
v4 v3
w3
v4
(b) Non-Bipartite graph
(a) Bipartite graph
The Bipartite graphs are useful in optimal matching and resource allocation problems, for example,
assigning courses to a set of instructors so that maximum number of courses can be offered.
Figures (c) and (d) show a graph which represents instructors and courses. Assuming an instructor can take
one or more courses but is allowed to teach one course. Figure (c) shows a possible offering of
two courses. The figure (d) depicts the optimum offering of 3 courses.
I1 I1
C1 C1
I2 I2
C2 C2
I3 I3
C3 C3
I4 I4
C4 C4
I5 I5
(c) Offering of two courses (d) Offering of three courses
Graph Algorithms / Dr.A.Sattar /11
Special Graphs
Articulation Vertex
An articulation vertex in connected graph is a special vertex whose deletion disconnects
one or more components of graph.
Figure shows a connected graph with an articulation vertex( colored red).
v3 v5 v7 v10 v15
v4 v9 v13
Articulation vertices play a crucial role in network security. Efficient algorithms are available
to find such vertices in a large network.
1 if (vi, vj) ∈E
aij =
0 otherwise
The definition implies that entry in the ith row and jth column of the matrix is 1
if a link exists between the ith and jth vertex; otherwise, it is 0.
The size |V|x|V| of adjacency matrix is dependent on the number of vertices. The
memory requirement is θ(|V|2)
Let G=(V,E) be a graph, and Adj(u) be the linked list corresponding to vertex u, then
for all v,
v ∈ Adj(u), if (u ,v )∈ E.
The vertices belonging to Adj(u) are called u’s immediate neighbors, or adjacent vertices.
If a graph has any subgraph (which is not reachable from the initial vertex),
the procedure may be re-started by choosing a vertex from the unvisited subgraph.
Step #4: Remove an element from the queue. Process and mark it as visited
Step #5: Enqueue all adjacent vertices of the processed vertex. Go to Step # 3.
The same algorithm may be applied to a subgraph, which contains any unvisited vertices.
Visualization
Graph Algorithms / Dr.A.Sattar /35
Analysis of Breadth First Search
Worst Case
The running time for BFS consists of following major components
Ti = Initializing vertices T
Tq = Queuing and Dequeuing
Ts = Scanning Adjacency list
The Graph G(V,E) has |V| vertices and |E| edges. Each vertex is initialized once. Therefore,
Ti = |V|
The queuing and dequeuing operations take O(1) time, and each vertex is queued
and dequeued once,
Tq = 2|V|.O(1)
The scanning of Adjacency list takes place for each vertex. In worst case all links are
are examined. The total time is proportional to the number of edges scanned. Since |E| is
the number of edges in G,
Ts = |E|
Graph Algorithms/Dr.A.Sattar
Graph Algorithms / Dr.A.Sattar /36
Depth First Search
Strategy
The Depth First Search (DFS) is one of the standard graph traversal methods. Each node
is visited once only. The method proceeds by first visiting all distant neighbors
If a graph has any sub-graph (which is not reachable from the initial vertex),
the procedure is re-started by choosing a vertex from the unvisited sub-graph.
Step #4: Pop off an element from the stack. Process and mark it as visited
Step #5: Push to stack adjacent vertices of the processed vertex. Go to Step # 3.
The same algorithm is applied to a subgraph, which contains any unvisited vertices.
The DFS can find shortest distance from the source vertex to a distant vertex
Visualization
Graph Algorithms / Dr.A.Sattar /55
Analysis of Depth First Search
Worst Case
The running time for DFS consists of following major components
Ti = Initializing vertices T
Tp = pushing and popping
Ts = Scanning Adjacency list
The Graph G(V,E) has |V| vertices and |E| edges. Each vertex is initialized once. Therefore,
Ti = |V|
The pushing and popping operations take O(1) time, and each vertex is pushed
and popped once,
Tp = 2|V|.O(1)
The scanning of Adjacency list takes place for each vertex. The total time is
proportional to the number of edges scanned. Since |E| is the number of edges in G, in worst
case all edges are examined. Therefore,
Ts = |E|
There can be several spanning trees for a graph. Figure shows some of the trees
for the graph with vertices v1,v2,v3,v4
v1 v2
v1 v2 v1 v2 v1 v2 v1 v2
v4 v3
v4 v3 v4 v3 v4 v3 v4 v3
Graph
Spanning Trees
One of the spanning trees has smallest sum of all the weights associated with the
edges. This tree is called minimum spanning tree (mst).
Figure shows a sample weighted graph, some of the spanning trees, and the minimum
spanning tree.
20 20 20 20 20
v1 v2 v1 v2 v1 v2 v1 v2 v1 v2
30 50 40
10 10 30 10 10 40
50
v4 60 v3 v4 v3 v4 60 v3 v4 60 v3 v4 v3
• The air travel routes can be selected so that the travel time or travel cost is least.
• Linking a group of islands with bridges so that total bridge span length is minimum
Two important algorithms for creating a minimum spanning tree for a graph,
named after their inventors, are Kruskal’s algorithm and Prim’s algorithm.
Example
Edge EF is extracted. It is added to the spanning tree .
Example
Note that the minimum spanning tree includes all of the graph vertices.
In actual implementation, the edges can be sorted by using an efficient algorithm such as quick sort.
Alternatively, a Priority Queue, based on min-heap, can be used. The edges are retrieved in
non-decreasing order by dequeue operation, as shown in the preceding example.
The problem of detection of cycle can be handled by using a Union set. A Union set is a set
of disjoint sets of vertices. For example, if V={a ,b, c, d ,e} is the vertex set, then Union Set
is defined as the set UV={ {a}, {b}, {c}, {c}, {d}, {e} } In order to form the minimum spanning
tree, an edge is extracted from the priority queue. Next, the elements of UV are examined.
If the vertices belong to the same disjoint set, the edge is discarded; otherwise, the set UV
is updated by merging the disjoint sets.
For example, if at stage the UV consists of elements {a}, {b}, { c, e}, {d}, and edge ed is
extracted, then the Union set would be updated by merging the subsets {c, e} and {d}. In other words,
the updated UV will be to {{a}, {b}, {c, d, e}}. Again, assuming an edge ce is extracted.
Since e and d belong to the same set {c, d, e} the edge will be discarded Again, assume that the edge ab
is extracted. Since the vertices a, b belong to different sets, the corresponding disjoints set, namely,
{a}, {b} will be merged. Thus, the updated UV would be UV={{a, b}, {c, d, e} }. Next , assume
that edge bc is selected, the sets {a, b} and {c, d, e} would be merged i.e UV={a, b, c, d, e}
Edge Weight Edge Action UV={{v1}, {v2}, {v3}, {v4}, {v5}, {v6}, {v7} }
(v2,v3) 10 (v2,v3) added { {v1}, {v2, v3}, {v4}, {v5}, {v6}, {v7} }
MST-KRUSKAL(G,W)
1 T←φ ►Initialize Minimum Spanning Tree
2 VS←φ ► Initialize Union set VS
∈
3 for each vertex v V
4 do VS ← VS U{v} ► Add Vertex sets to union set
5 for each (u, v) ∈ E ►Create a priority queue of edges and weights
6 do ENQUEUE(Q,u,v,w) ► weights are keys (priorities)
7 while |VS| >1 do ► Continue until all vertices form a single set of cardinality 1
8 (u,v) ←DEQUEUE(Q) ►Remove an edge (u,v) from the queue
9 if u, v belong to different sets VS1∈ VS and VS2 VS ∈
10 then VS ←VS – VS1 ► remove set VS1 from VS
11 VS←VS - VS2►remove set VS2 from VS
12 VS ← VS U ( VS1 U VS2) ►Join sets VS1 and VS2 , add the union to VS
13 T←(u, v) ►Add the selected edge to the spanning tree
14 return T
Visualization
The total time to find sets VS1 and VS2 and replacing them by their union
is at most O(|E|)
Thus, on the whole Kruskal’s algorithm runs in time O(|E|. lg| E|) + O(|E|)+O(|V|)
.
Let V be the vertex set for a graph G. Let T be the minimum spanning tree for G. The
Prim’s algorithm proceeds as follows:
Step #:1 Select some vertex s in V , as the starting vertex.
Step # 3: Repeat Step #:4 through Step #:6 until the set V is empty.
Step #5 :Choose the vertex u in V which has the minimum distance from vertex v in S.
Step #6: Remove vertex u from V and add it to S. Move edge (v ,u) to T.
Example
Initially, the set V contains all of the graph vertices. Another set G holds the processed
vertices. First, vertex A is chosen. It is deleted from V and placed in set G. A is marked as
selected, and shown in pink color.
Example
All vertices in set V, which are linked to the vertices in set S, are examined. The vertex
which has the shortest distance is selected, and placed in set S. The selected vertices form
path of the Minimum Spanning Tree.
Vertices B, I, J in set V are linked to vertex A in set S, and have distances 10, 30, 28
respectively. Since B has minimum distance 10, it is selected . The corresponding edge of
the subgraph, or segment of minimum spanning tree, is shown in red color.
Example
Vertices I, J in set V are linked to vertex A, and have distances 30, 28. Vertices C, J in set V
are linked to vertex B in set S and have the distances 15, 17. Since vertex C has the minimum
distance 15 , it is selected. The vertex C is removed from set V, and placed in set S.
Example
Vertex I in set V is linked to vertex A, and has distances 30. Vertex J in set V is linked to
vertices A, B and C in set S and has the distances 28, 17,40 . Vertex D in set V is linked to
vertex C in S and has distance 45. Since vertex J has the minimum distance 17 , it is
selected. The vertex J is removed from set V, and placed in set S.
Example
Vertex I in V is linked to vertices A and J in S, and has distances 30, 47. Vertex
Vertex D in V is linked to vertices C, J in S, and has distances 45, 57. Vertex E in V is linked
to J in S and has distance 12. Vertex H in S is linked to J in S and distance 39. Vertex K in S is
linked to vertex J in S, and has distance 32. Since E has the minimum distance 12 , it is
selected. The vertex E is removed from set V, and placed in set S.
Example
Vertex I in V is linked to vertices A and J in S, and has distances 30, 47. Vertex
Vertex D in V is linked to vertices C, J, E in S, and has distances 45, 57,18. H in S is linked
to J in S and has distance 39. Vertex K in S is linked to vertices J and E in S, and has
distances 32, 14. Vertex F in V is linked to E in S and has distance 8. Since F has the
minimum distance 8 , it is selected. The vertex F is removed from set V, and placed in set S.
Example
Vertex I in V is linked to vertices A and J in S, and has distances 30, 47. Vertex D in V is
linked to vertices C, J, E in S, and has distances 45, 57,18. H in S is linked to J in S and has
distance 39. Vertex K in S is linked to vertices J, E and F in S, and has distances 32, 14, 19 .
Vertex G in V linked to F in S and has distance 50 Since K has the minimum distance 14 , it
is selected. The vertex K is removed from set V, and placed in set S.
Example
Vertex I in V is linked to vertices A and J in S, and has distances 30, 47. Vertex D in V is
linked to vertices C, J, E in S, and has distances 45, 57,18. H in S is linked to J,K in S and has
distances 39, 29. Vertex G in V linked to F,K in S and has distances 50,55 Since D has the
minimum distance 18 , it is selected. The vertex G is removed from set V, and placed in set S.
Example
Vertex I in V is linked to vertices A and J in S, and has distances 30, 47. H in S is linked to
J,K in S and has distances 39, 29. Vertex G in V linked to F,K in S and has distances 50,55
Since H has the minimum distance 29 , it is selected. The vertex H is removed from set V,
and placed in set S.
Example
Vertex I in V is linked to vertices A, J, H in S, and has distances 30, 47, 14. Vertex G in V
linked to F,K,H in S and has distances 50,55,45 Since I has the minimum distance 14 , it is
selected. The vertex I is removed from set V, and placed in set S.
Example
Vertex G in V linked to F,K,H in S and has distances 50,55,45 Since G has the minimum
distance 45 , it is selected. The vertex G is removed from set V, and placed in set S.
All the vertices have been processed. The algorithm terminates.
The total distance of all the selected edges is 182.
The Minimum Spanning Tree, shown in red, has total length of 182.
Figure shows a sample graph and the shortest paths from a vertex A.
Weighted Directed Graph
Shortest path
The shortest path algorithm has several applications. It can be used, for example, to find
shortest route between two cities
An efficient algorithm for single-source shortest path is known as Dijkstra’s algorithm,
named after its inventor.
Graph Algorithms / Dr.A.Sattar /105
Single Source Shortest Paths
Dijkstra’s Algorithm
The Dijkstra’s algorithm determines shortest paths from a single vertex in a weighted
directed graph. The working of Dijkstra’s algorithm is similar to Prim’s algorithm. It
repeatedly computes the distances between a source vertex and the vertices being explored,
and selects the minimum distance from among the feasible paths. It is categorized as greedy
algorithm.
Let V be the vertex set for a graph G. Let d be an array that stores shortest distances. The
algorithm proceeds as follows:
Step #:1 Initialize elements to some large number
Step # 3: Repeat Step #:4 through Step #:5 until the set V is empty.
Step # 4: Examine vertices in S which are linked to vertices in V. Choose the vertex u
in V which has the shortest distance from the source. Store this distance in d[u]
DIJKSTRA(G, s)
1 for each vertex v ∈ V
2 do d[v] ← ∞ ► Array d [V\stores minimum distances .
3 S← φ ► S contains selected vertices
4 S←S U {s} ► starting vertex is added to S
5 V←V-{s} ► Starting vertex is removed from V
6 while V ≠ φ do
7 for each vertex u∈ S do ►select a vertex u in S
8 for each vertex v ∈ Adj[u] do ►Examine all vertices which are linked to u
9 if d[u] >d[u]+ w(u,v) ► Check if the d[u] is smaller
10 then d[u]←d[u]+w(u,v) ► If yes, replace d[u] with sum of w(u,v)
11 w← v ► store vertex v in w
12 V ←V - {w} ►remove vertex w from V
13 S ← S U {w} ►add vertex w to S
Visualization