Unit 5
Unit 5
Graphs- definition - types of graphs, basic terminologies, representations of graph, topological sort;
Graph Traversals- breadth first search, depth first search; Shortest Path Algorithms - unweighted shortest path,
Dijkstra’s algorithm; Minimum Spanning Trees - prim’s algorithm, kruskal’s algorithm; Applications of Graphs.
Graph:
A graph is data structure that consists of following two components.
A finite set of vertices also called as nodes.
A finite set of ordered pair of the form (u, v) called as edge.
(or)
A graph G=(V, E) is a collection of two sets V and E, whereV→
Finite number of vertices
E→ Finite number of Edges,
Graph Definition:
A graph is defined as Graph is a collection of vertices and arcs which connects vertices in the graph. A graph G is
represented as G = ( V , E ), where V is set of vertices and E is set of edges.
Types of Graphs:
1.Undirected Graph
2. Directed Graph
A graph in which any V node is adjacent to all other nodes present in the graph is known as a complete graph. An
undirected graph contains the edges that are equal to edges = n(n-1)/2 where n is the number of vertices present in
the graph. The following figure shows a complete graph.
4. Regular Graph
Regular graph is the graph in which nodes are adjacent to each other, i.e., each node is accessible from any other
node.
5. Cycle Graph
A graph having cycle is called cycle graph. In this case the first and last nodes are the same. A closed simple path
is a cycle.
6. Acyclic Graph
A graph without cycle is called acyclic graphs.
7. Weighted Graph
A graph is said to be weighted if there are some non negative value assigned to each edges of the graph. The
value is equal to the length between two vertices. Weighted graph is also called a network.
Graph Terminology:
1. Vertex : An individual data element of a graph is called as Vertex. Vertex is also known as node. In above
example graph, A, B, C, D & E are known as vertices.
2. Edge : An edge is a connecting link between two vertices. Edge is also known as Arc. An edge is represented as
(starting Vertex, ending Vertex).
1. Undirected Edge - An undirected edge is a bidirectional edge. If there is an undirected edge between vertices A
and B then edge (A , B) is equal to edge (B , A).
2. Directed Edge - A directed edge is a unidirectional edge. If there is a directed edge between vertices A and B
then edge (A , B) is not equal to edge (B , A).
3. Weighted Edge - A weighted edge is an edge with cost on it.
Graph Representations
1. Adjacency Matrix
2. Adjacency List
3. Adjacency Multilists
1.Adjacency Matrix
In this representation, graph can be represented using a matrix of size total number of vertices by total number of
vertices; means if a graph with 4 vertices can be represented using a matrix of 4X4 size.In this matrix, rows and
columns both represent vertices.
This matrix is filled with either 1 or 0. Here, 1 represents there is an edge from row vertex to column vertex and 0
represents there is no edge from row vertex to column vertex.
Adjacency Matrix : let G = (V, E) with n vertices, n 1. The adjacency matrix of G is a 2-dimensional n n
matrix, A, A(i, j) = 1 iff (vi, vj) E(G) (vi, vj for a diagraph), A(i, j) = 0 otherwise.
2. Adjacency List
In this representation, every vertex of graph contains list of its adjacent vertices. The n rows of the adjacency
matrix are represented as n chains. The nodes in chain I represent the vertices that are adjacent to vertex i.
It can be represented in two forms. In one form, array is used to store n vertices and chain is used to store its
adjacencies. Example:
So that we can access the adjacency list for any vertex in O(1) time. Adjlist[i] is a pointer to to first node in the
adjacency list for vertex i. Structure is
#define MAX_VERTICES 50
typedef struct node *node_pointer;
typedef struct node {
int vertex;
struct node *link;
};
node_pointer graph[MAX_VERTICES];
int n=0; /* vertices currently in use */
example: consider the following directed graph representation implemented using linked list
Graph
Instead of chains, we can use sequential representation into an integer array with size n+2e+1. For 0<=i<n,
Array[i] gives starting point of the list for vertex I, and array[n] is set to n+2e+1. The adjacent vertices of node I
are stored sequentially from array[i].
For an undirected graph with n vertices and e edges, linked adjacency list requires an array of size n and 2e chain
nodes. For a directed graph, the number of list nodes is only e. the out degree of any vertex may be determined by
counting the number of nodes in its adjacency list. To find in-degree of vertex v, we have to traverse complete
list.
3.Adjacency Multilists
In the adjacency-list representation of an undirected graph each edge (u, v) is represented by two entries one on the
list for u and the other on tht list for v. As we shall see in some situations it is necessary to be able to determin ie ~
nd enty for a particular edge and mark that edg as having been examined. This can be accomplished easilyif the
adjacency lists are actually maintained as multilists (i.e., lists in which nodes may be shared among several lists).
For each edge there will be exactly one node but this node will be in two lists (i.e. the adjacency lists for each of
the two nodes to which it is incident).
For adjacency multilists, node structure is
typedef struct edge *edge_pointer;
typedef struct edge {
short int marked;
int vertex1, vertex2;
edge_pointer path1, path2;
};
edge_pointer graph[MAX_VERTICES];
Lists: vertex 0: N0->N1->N2, vertex
1: N0->N3->N4vertex 2: N1-
In the Directed Acyclic Graph, Topological sort is a way of the linear ordering of vertices v1, v2, ….
vN in such a way that for every directed edge x → y, x will come before y in the ordering.
For that, we will maintain an array T[ ], which will store the ordering of the vertices in topological
order. We will store the number of edges that are coming into a vertex in an
array in_degree[N], where the i-th element will store the number of edges coming into the
vertex i. We will also store whether a certain vertex has been visited or not in visited[N]. We will
follow the belo steps:
• First, take out the vertex whose in_degree is 0. That means there is no edge that is coming
into that vertex.
• We will append the vertices in the Queue and mark these vertices as visited.
• Now we will traverse through the queue and in each step we will dequeue() the front element
in the Queue and push it into the T.
• Now, we will put out all the edges that are originated from the front vertex which means we
will decrease the in_degree of the vertices which has an edge with the front vertex.
• Similarly, for those vertices whose in_degree is 0, we will push it in Queue and also mark
that vertex as visited. ( Hope you must be thinking its BFS but with in_degree)
Illustration
GRAPH TRAVERSAL
traversals are :
The Breadth first search was one of the systematic approaches for exploring
and searching the vertices/nodes in a given graph. The approach is called
"breadth-first" because from each vertex ‘v’ that wevisit, we search as broadly
as possible by next visiting all the vertices adjacent to v.
It can also be used to find out whether a node is reachable from a givennode or
not.
It is applicable to both directed and undirected graphs.
Queue is used in the implementation of the breadth first search.
ALGORITHM
Procedure bfs()
{
//BFS uses Queue data structure
Queue q=new LinkedList();
q.add(this.rootNode);
printNode(this.rootNode);
rootNode.visited=true;
while(!q.isEmpty())
{
Node n=(Node)q.remove(); Node child=null;
while((child=getUnvisitedChildNode(n))!=null)
{
child.visited=
true;
printNode(ch
ild);
q.add(child);
}
}
//Clear visited property of nodes
clearNodes();
}
Procedure
Step -1 Select the start vertex/source vertex. Visit the vertex and mark itas one
(1) (1 represents visited vertex).
Step -2 Enqueue the
vertex.Step -3
Dequeue the
vertex.
Step -4 Find the Adjacent vertices.
Step -5 Visit the unvisited adjacent vertices and mark the distance as 1.Step -
6 Enqueue the adjacent vertices.
Step -7 Repeat from Step – 3 to Step – 5 until the queue becomes empty.
Ex : A B
Vertices Visited
Vertices
A 1
C D B 0 1
C 0 1
D 0 1
Enqueue A B C D
Dequeue A B C D
Vertices Visited
Vertices
A B C 1
A 0 1
B 0 1
D 0 1
C D
E 0 1
Enqueue C A B D
E
E Dequeue C A B D
E
APPLICATIONS
Breadth-first search can be used to solve many problems in graph theory, forexample.
Uses
Testing whether graph is connected. Computing a
spanning forest of graph.
Computing, for every vertex in graph, a path with the minimum numberof edges between
start vertex and current vertex or reporting that no such path exists.
Computing a cycle in graph or reporting that no such cycle exists.
DEPTH FIRST SEARCH
Depth first search works by taking a node, checking its neighbors, expanding the first
node it finds among the neighbors, checking if that expanded node is our destination,
and if not, continue exploring morenodes.
In depth-first search, edges are explored out of the most recentlydiscovered vertex v that
still has unexplored edges leaving it.
When all of v' s edges have been explored, the search "backtracks" toexplore edges
leaving the vertex from which v was discovered.
This process continues until we have discovered all the vertices that arereachable from the original
source vertex.
If any undiscovered vertices remain, then one of them is selected as anew source and the
search is repeated from that source.
This entire process is repeated until all vertices are discovered.Stack is used in the
implementation of the depth first search.
In DFS, the basic data structures for storing the adjacent nodes is stack.
Procedure:
Applications of DFS :
Dijkstra’s algorithm is a popular algorithms for solving many single-source shortest path problems
having non-negative edge weight in the graphs i.e., it is to find the shortest distance between two
vertices on a graph.
The algorithm maintains a set of visited vertices and a set of unvisited vertices. It starts at the source
vertex and iteratively selects the unvisited vertex with the smallest tentative distance from the source.
It then visits the neighbors of this vertex and updates their tentative distances if a shorter path is
found. This process continues until the destination vertex is reached, or all reachable vertices have
been visited.
For example, It can be used in the routing protocols for computer networks and also used by map
systems to find the shortest path between starting point and the Destination .
• So Basically, Dijkstra’s algorithm starts at the node source node we choose and then it
analyzes the graph condition and its paths to find the optimal shortest distance between
the given node and all other nodes in the graph.
• Dijkstra’s algorithm keeps track of the currently known shortest distance from each node
to the source node and updates the value after it finds the optimal path once the algorithm
finds the shortest path between the source node and destination node then the specific
node is marked as visited.
Basics requirements for Implementation of Dijkstra’s Algorithm
1. Graph: Dijkstra’s Algorithm can be implemented on any graph but it works best with a
weighted Directed Graph with non-negative edge weights and the graph should be
represented as a set of vertices and edges.
2. Source Vertex: Dijkstra’s Algorithm requires a source node which is starting point for the
search.
14
3. Destination vertex: Dijkstra’s algorithm may be modified to terminate the search once a
specific destination vertex is reached.
4. Non-Negative Edges: Dijkstra’s algorithm works only on graphs that have positive
weights this is because during the process the weights of the edge have to be added to find
the shortest path. If there is a negative weight in the graph then the algorithm will not
work correctly. Once a node has been marked as visited the current path to that node is
marked as the shortest path to reach that node.
• Set the non-visited node with the smallest current distance as the current node.
• For each neighbor, N of the current node adds the current distance of the adjacent node
with the weight of the edge connecting 0->1. If it is smaller than the current distance of
Node, set it as the new current distance of N.
• Mark the current node 1 as visited.
• Go to step 2 if there are any nodes are unvisited.
15
How does Dijkstra’s Algorithm works?
Let’s see how Dijkstra’s Algorithm works with an example given below:
Dijkstra’s Algorithm will generate the shortest path from Node 0 to all other Nodes in the graph.
Dijkstra’s Algorithm
The algorithm will generate the shortest path from node 0 to all the other nodes in the graph.
For this graph, we will assume that the weight of the edges represents the distance between two
nodes.
As, we can see we have the shortest path from,
Node 0 to Node 1, from
Node 0 to Node 2, from
Node 0 to Node 3, from
Node 0 to Node 4, from
Node 0 to Node 6.
• The Distance from the source node to itself is 0. In this example the source node is 0.
• The distance from the source node to all other node is unknown so we mark all of them as
infinity.
16
Example: 0 -> 0, 1-> ∞,2-> ∞,3-> ∞,4-> ∞,5-> ∞,6-> ∞.
• we’ll also have an array of unvisited elements that will keep track of unvisited or
unmarked Nodes.
• Algorithm will complete when all the nodes marked as visited and the distance between
them added to the path. Unvisited Nodes:- 0 1 2 3 4 5 6.
Step 1: Start from Node 0 and mark Node as visited as you can check in below image visited Node is
marked red.
Dijkstra’s Algorithm
Step 2: Check for adjacent Nodes, Now we have to choices (Either choose Node1 with distance 2 or
either choose Node 2 with distance 6 ) and choose Node with minimum distance. In this step Node
1 is Minimum distance adjacent Node, so marked it as visited and add up the distance.
Distance: Node 0 -> Node 1 = 2
17
Dijkstra’s Algorithm
Step 3: Then Move Forward and check for adjacent Node which is Node 3, so marked it as visited
and add up the distance, Now the distance will be:
Distance: Node 0 -> Node 1 -> Node 3 = 2 + 5 = 7
Dijkstra’s Algorithm
Step 4: Again we have two choices for adjacent Nodes (Either we can choose Node 4 with distance
10 or either we can choose Node 5 with distance 15) so choose Node with minimum distance. In this
step Node 4 is Minimum distance adjacent Node, so marked it as visited and add up the distance.
Distance: Node 0 -> Node 1 -> Node 3 -> Node 4 = 2 + 5 + 10 = 17
18
Dijkstra’s Algorithm
Step 5: Again, Move Forward and check for adjacent Node which is Node 6, so marked it as visited
and add up the distance, Now the distance will be:
Distance: Node 0 -> Node 1 -> Node 3 -> Node 4 -> Node 6 = 2 + 5 + 10 + 2 = 19
Dijkstra’s Algorithm
So, the Shortest Distance from the Source Vertex is 19 which is optimal one.
19
Prim's Algorithm
In this article, we will discuss the prim's algorithm. Along with the algorithm, we will also see the
complexity, working, example, and implementation of prim's algorithm.
Before starting the main topic, we should discuss the basic and important terms such as spanning tree
and minimum spanning tree.
Minimum Spanning tree - Minimum spanning tree can be defined as the spanning tree in which the
sum of the weights of the edge is minimum. The weight of the spanning tree is the sum of the weights
given to the edges of the spanning tree.
Prim's Algorithm is a greedy algorithm that is used to find the minimum spanning tree from a graph.
Prim's algorithm finds the subset of edges that includes every vertex of the graph such that the sum of
the weights of the edges can be minimized.
Prim's algorithm starts with the single node and explores all the adjacent nodes with all the connecting
edges at every step. The edges with the minimal weights causing no cycles in the graph got selected.
Prim's algorithm is a greedy algorithm that starts from one vertex and continue to add the edges with
the smallest weight until the goal is reached. The steps to implement the prim's algorithm are given as
follows -
20
Example of prim's algorithm
Now, let's see the working of prim's algorithm using an example. It will be easier to understand the
prim's algorithm using an example.
Step 1 - First, we have to choose a vertex from the above graph. Let's choose B.
Step 2 - Now, we have to choose and add the shortest edge from vertex B. There are two edges from
vertex B that are B to C with weight 10 and edge B to D with weight 4. Among the edges, the edge
BD has the minimum weight. So, add it to the MST.
21
Step 3 - Now, again, choose the edge with the minimum weight among all the other edges. In this case,
the edges DE and CD are such edges. Add them to MST and explore the adjacent of C, i.e., E and A.
So, select the edge DE and add it to the MST.
Step 4 - Now, select the edge CD, and add it to the MST.
22
Step 5 - Now, choose the edge CA. Here, we cannot select the edge CE as it would create a cycle to
the graph. So, choose the edge CA and add it to the MST.
So, the graph produced in step 5 is the minimum spanning tree of the given graph. The cost of the MST
is given below -
Algorithm
1. Step 1: Select a starting vertex
2. Step 2: Repeat Steps 3 and 4 until there are fringe vertices
3. Step 3: Select an edge 'e' connecting the tree vertex and fringe vertex that has minimum weig
ht
4. Step 4: Add the selected edge and the vertex to the minimum spanning tree T
5. [END OF LOOP]
6. Step 5: EXIT
23
Kruskal's Algorithm
In this article, we will discuss Kruskal's algorithm. Here, we will also see the complexity, working,
example, and implementation of the Kruskal's algorithm.
But before moving directly towards the algorithm, we should first understand the basic terms such as
spanning tree and minimum spanning tree.
Minimum Spanning tree - Minimum spanning tree can be defined as the spanning tree in which the
sum of the weights of the edge is minimum. The weight of the spanning tree is the sum of the weights
given to the edges of the spanning tree.
Kruskal's Algorithm is used to find the minimum spanning tree for a connected weighted graph. The
main target of the algorithm is to find the subset of edges by using which we can traverse every vertex
of the graph. It follows the greedy approach that finds an optimum solution at every stage instead of
focusing on a global optimum.
In Kruskal's algorithm, we start from edges with the lowest weight and keep adding the edges until the
goal is reached. The steps to implement Kruskal's algorithm are listed as follows -
24
Example of Kruskal's algorithm
Now, let's see the working of Kruskal's algorithm using an example. It will be easier to understand
Kruskal's algorithm using an example.
The weight of the edges of the above graph is given in the below table –
Now, sort the edges given above in the ascending order of their weights.
25
Step 1 - First, add the edge AB with weight 1 to the MST.
Step 2 - Add the edge DE with weight 2 to the MST as it is not creating the cycle.
Step 3 - Add the edge BC with weight 3 to the MST, as it is not creating any cycle or loop.
Step 4 - Now, pick the edge CD with weight 4 to the MST, as it is not forming the cycle.
26
Step 5 - After that, pick the edge AE with weight 5. Including this edge will create the cycle, so discard
it.
Step 6 - Pick the edge AC with weight 7. Including this edge will create the cycle, so discard it.
Step 7 - Pick the edge AD with weight 10. Including this edge will also create the cycle, so discard it.
So, the final minimum spanning tree obtained from the given weighted graph by using Kruskal's
algorithm is -
Now, the number of edges in the above tree equals the number of vertices minus 1. So, the algorithm
stops here.
27
Algorithm
1. Step 1: Create a forest F in such a way that every vertex of the graph is a separate tree.
2. Step 2: Create a set E that contains all the edges of the graph.
3. Step 3: Repeat Steps 4 and 5 while E is NOT EMPTY and F is not spanning
4. Step 4: Remove an edge from E with minimum weight
5. Step 5: IF the edge obtained in Step 4 connects two different trees, then add it to the forest F
Application of graphs:
28