0% found this document useful (0 votes)
9 views

Unit 5 Graph (2)

The document provides a comprehensive overview of graph theory, defining key concepts such as vertices, edges, and types of graphs (directed, undirected, weighted). It discusses graph traversal algorithms like Breadth First Search (BFS) and Depth First Search (DFS), as well as spanning trees and their properties, including minimum spanning trees and algorithms like Kruskal's and Prim's. Additionally, it covers shortest path algorithms, including Dijkstra's and the Floyd-Warshall algorithm, highlighting their applications and methodologies.

Uploaded by

Yuvika Miglani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Unit 5 Graph (2)

The document provides a comprehensive overview of graph theory, defining key concepts such as vertices, edges, and types of graphs (directed, undirected, weighted). It discusses graph traversal algorithms like Breadth First Search (BFS) and Depth First Search (DFS), as well as spanning trees and their properties, including minimum spanning trees and algorithms like Kruskal's and Prim's. Additionally, it covers shortest path algorithms, including Dijkstra's and the Floyd-Warshall algorithm, highlighting their applications and methodologies.

Uploaded by

Yuvika Miglani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

Graph

A graph can be defined as group of vertices and edges that are used to connect these
vertices. A graph can be seen as a cyclic tree, where the vertices (Nodes) maintain any
complex relationship among them instead of having parent child relationship.

Definition
A graph G can be defined as an ordered set G(V, E) where V(G) represents the set of vertices
and E(G) represents the set of edges which are used to connect these vertices.
A Graph G(V, E) with 5 vertices (A, B, C, D, E) and six edges ((A,B), (B,C), (C,E), (E,D), (D,B),
(D,A)) is shown in the following figure.
Directed and Undirected Graph
A graph can be directed or undirected. However, in an undirected graph, edges are not
associated with the directions with them. An undirected graph is shown in the above figure
since its edges are not attached with any of the directions. If an edge exists between vertex A
and B then the vertices can be traversed from B to A as well as A to B.

In a directed graph, edges form an ordered pair. Edges represent a specific path from some
vertex A to another vertex B. Node A is called initial node while node B is called terminal node.
Graph Terminology

Path
A path can be defined as the sequence of nodes that are followed in order to reach some
terminal node V from the initial node U.

Closed Path
A path will be called as closed path if the initial node is same as terminal node. A path will
be closed path if V0=VN.

Simple Path
If all the nodes of the graph are distinct with an exception V0=VN, then such path P is
called as closed simple path.

Cycle
A cycle can be defined as the path which has no repeated edges or vertices except the
first and last vertices.
Connected Graph
A connected graph is the one in which some path exists between every two vertices (u, v)
in V. There are no isolated nodes in connected graph.

Complete Graph
A complete graph is the one in which every node is connected with all other nodes. A
complete graph contain n(n-1)/2 edges where n is the number of nodes in the graph.
Weighted Graph
In a weighted graph, each edge is assigned with some data such as length or weight.
The weight of an edge e can be given as w(e) which must be a positive (+) value
indicating the cost of traversing the edge.

Digraph
A digraph is a directed graph in which each edge of the graph is associated with some
direction and the traversing can be done only in the specified direction.

Loop
An edge that is associated with the similar end points can be called as Loop.

Adjacent Nodes
If two nodes u and v are connected via an edge e, then the nodes u and v are called as
neighbor's or adjacent nodes.

Degree of the Node


A degree of a node is the number of edges that are connected with that node. A node
with degree 0 is called as isolated node.
Graph Representation

By Graph representation, we simply mean the technique which is to be used in order


to store some graph into the computer's memory.
There are two ways to store Graph into the computer's memory.

1. Sequential Representation

In sequential representation, we use adjacency matrix to store the mapping


represented by vertices and edges. In adjacency matrix, the rows and columns are
represented by the graph vertices. A graph having n vertices, will have a dimension n
x n.

An entry Mij in the adjacency matrix representation of an undirected graph G will be 1 if


there exists an edge between Vi and Vj.
Linked Representation
In the linked representation, an adjacency list is used to store the Graph into the computer's
memory.
Consider the undirected graph shown in the following figure and check the adjacency list
representation.
Graph Traversal Algorithm

We can traverse all the vertices of the graph.

Traversing the graph means examining all the nodes and vertices of the graph. There are two
standard methods by using which, we can traverse the graphs. Lets discuss each one of them
in detail.

• Breadth First Search


• Depth First Search
Breadth First Search (BFS) Algorithm

Breadth first search is a graph traversal algorithm that starts traversing the graph from root
node and explores all the neighboring nodes. Then, it selects the nearest node and explore
all the unexplored nodes. The algorithm follows the same process for each of the nearest
node until it finds the goal. The data structure which is being used in DFS is queue.

The algorithm of breadth first search is given below. The algorithm starts with examining
the node A and all of its neighbors. In the next step, the neighbors of the nearest node of A
are explored and process continues in the further steps. The algorithm explores all
neighbors of all the nodes and ensures that each node is visited exactly once and no node
is visited twice.
Algorithm
Solution:

Minimum Path P can be found by applying breadth first search algorithm that will begin at
node A and will end at E. the algorithm uses two queues,
namely QUEUE1 and QUEUE2. QUEUE1 holds all the nodes that are to be processed
while QUEUE2 holds all the nodes that are processed and deleted from QUEUE1.
Lets start examining the graph from Node A.
Depth First Search (DFS) Algorithm

Depth first search (DFS) algorithm starts with the initial node of the graph G, and then
goes to deeper and deeper until we find the goal node or the node which has no
children. The algorithm, then backtracks from the dead end towards the most recent
node that is yet to be completely unexplored.

The data structure which is being used in DFS is stack. The process is similar to BFS
algorithm. In DFS, the edges that leads to an unvisited node are called discovery edges
while the edges that leads to an already visited node are called block edges.
Push H onto the stack
Spanning Tree

Before knowing about the spanning trees, we should know about some graphs.

The following are the types of graphs:

• Undirected graph: An undirected graph is a graph in which all the edges do not point to
any particular direction, i.e., they are not unidirectional; they are bidirectional.
It can also be defined as a graph in which set of V vertices and set of E edges, each edge
connecting two different vertices.

• Connected graph: A connected graph is a graph in which a path always exists from a
vertex to any other vertex.A graph is connected if we can reach any vertex from any other
vertex by following edges in either direction.

• Directed graph: A directed graph is defined as a graph in which set of V vertices and set
of Edges, each connecting two different vertices,but it is not mandatory that node points in
the opposite direction also.
What is a Spanning tree?

If we have a graph containing V vertices and E edges, then the graph can be represented as:
G(V, E)
If we create the spanning tree from the above graph, then the spanning tree would have the
same number of vertices as the graph, but the edges are not equal. The edges in the
spanning tree would be equal to the number of edges in the graph minus 1.
Suppose the spanning tree is represented as:
G`(V`, E`)
where,
V=V`
E`ϵ E -1
E`=|V| - 1
Let's understand through an example.
In the above tree, the total edge weight is 10 which is less than the above spanning trees;
therefore, the minimum spanning tree is a tree which is having an edge weight, i.e., 10.

Properties of Spanning tree

• A connected graph can contain more than one spanning tree. The spanning trees which are
minimally connected or we can say that the tree which is having a minimum total edge
weight would be considered as the minimum spanning tree.
• All the possible spanning trees that can be created from the given graph G would have the
same number of vertices, but the number of edges in the spanning tree would be equal to
the number of vertices in the given graph minus 1.
• The spanning tree does not contain any cycle. Let's understand this property through an
example.
• As we can observe in the above spanning trees that one edge has been removed. If we
do not remove one edge from the graph, then the tree will form a cycle, and that tree will
not be considered as the spanning tree.
• The spanning tree cannot be disconnected. If we remove one more edge from any of the
above spanning trees as shown below:
The above tree is not a spanning tree because it is disconnected now.
• If two or three edges have the same edge weight, then there would be more than two
minimum spanning trees. If each edge has a distinct weight, then there will be only one or
unique minimum spanning tree.
• A complete undirected graph can have nn-2 number of spanning trees where n is the
number of vertices in the graph. For example, the value of n is 5 then the number of
spanning trees would be equal to 125.
• Each connected and undirected graph contains at least one spanning tree.
• The disconnected graph does not contain any spanning tree.
• If the graph is a complete graph, then the spanning tree can be constructed by removing
maximum (e-n+1) edges. Let's understand this property through an example.
A complete graph is a graph in which each pair of vertices are connected. Consider the
complete graph having 3 vertices, which is shown below:
• According to this property, the maximum number of edges from the graph can be
formulated as (e-n+1) where e is the number of edges, n is the number of vertices. When we
substitute the value of e and n in the formula, then we get 1 value. It means that we can
remove maximum 1 edge from the graph to make a spanning tree. In the above spanning
trees, the one edge has been removed.

Application of Spanning trees


1. Consider n stations are to be linked using a communication network & laying of
communication links between any two stations involves a cost.The ideal solution would be to
extract a subgraph termed as minimum cost spanning tree.
2. Suppose you want to construct highways or railroads spanning several cities then we can
use the concept of minimum spanning trees.
3. Designing Local Area Networks.
4. Laying pipelines connecting offshore drilling sites, refineries and consumer markets.
Kruskal's Minimum Spanning Tree Algorithm:
After sorting: Weight Source Destination

1 7 6

2 8 2

2 6 5

4 0 1

4 2 6

6 8 3

7 2 8

7 7 8

8 0 7

8 1 2

9 3 4

10 5 4

11 1 7

14 3 5
Note: Since the number of edges included in the MST equals to (V - 1), so the algorithm stops here
Prim's Minimum Spanning Tree Algorithm

Prim's Algorithm starts with an arbitrary node and incrementally builds a minimum spanning tree by
adding edges that connect the tree to the rest of the graph. Here's a step-by-step overview of how
the algorithm works:

Initialization: Select an arbitrary node as the initial vertex for the minimum spanning tree.
Candidate Edge Selection: Identify all the edges that connect the current minimum spanning tree to
vertices not yet included in the tree. From these edges, choose the one with the smallest weight.
Add to Tree: Add the selected edge to the minimum spanning tree.
Repeat: Continue the process by considering the newly added vertex as part of the minimum
spanning tree and finding the next candidate edge.
Termination: Repeat steps 2-4 until all vertices are included in the minimum spanning tree, resulting
in a tree that spans all the original graph's nodes.
Dijkstra’s Algorithm

Dijkstra’s shortest path algorithm is similar to that of Prim’s


algorithm as they both rely on finding the shortest path locally to
achieve the global solution. However, unlike Prim’s algorithm, the
Dijkstra’s algorithm does not find the minimum spanning tree; it is
designed to find the shortest path in the graph from one vertex to
other remaining vertices in the graph. Dijkstra’s algorithm can be
performed on both directed and undirected graphs.
Since the shortest path can be calculated from single source vertex to
all the other vertices in the graph, Dijkstra’s algorithm is also called
single-source shortest path algorithm. The output obtained is called
shortest path spanning tree.

The Dijkstra’s algorithm is designed to find the shortest path between


two vertices of a graph. These two vertices could either be adjacent or
the farthest points in the graph. The algorithm starts from the source.
The inputs taken by the algorithm are the graph G {V, E}, where V is
the set of vertices and E is the set of edges, and the source vertex S.
And the output is the shortest path spanning tree.
Algorithm

Declare two arrays − distance[] to store the distances from the source vertex to the other vertices in
graph and visited[] to store the visited vertices.

Set distance[S] to ‘0’ and distance[v] = ∞, where v represents all the other vertices in the graph.

Add S to the visited[] array and find the adjacent vertices of S with the minimum distance.

The adjacent vertex to S, say A, has the minimum distance and is not in the visited array yet. A is
picked and added to the visited array and the distance of A is changed from ∞ to the assigned
distance of A, say d1, where d1 < ∞.

Repeat the process for the adjacent vertices of the visited vertices until the shortest path spanning
tree is formed.
Floyd Warshall Algorithm

The Floyd-Warshall algorithm, named after its creators Robert Floyd and Stephen
Warshall, is a fundamental algorithm in computer science and graph theory. It is used to
find the shortest paths between all pairs of nodes in a weighted graph. This algorithm is
highly efficient and can handle graphs with both positive and negative edge weights,
making it a versatile tool for solving a wide range of network and connectivity problems.

The Floyd Warshall Algorithm is an all pair shortest path algorithm unlike Dijkstra and
Bellman Ford which are single source shortest path algorithms. This algorithm works for
both the directed and undirected weighted graphs. But, it does not work for the
graphs with negative cycles (where the sum of the edges in a cycle is negative). It
follows Dynamic Programming approach to check every possible path going via every
possible node in order to calculate shortest distance between every pair of nodes.
Idea Behind Floyd Warshall Algorithm:
Suppose we have a graph G[][] with V vertices from 1 to N. Now we have to evaluate a
shortestPathMatrix[][] where shortestPathMatrix[i][j] represents the shortest path between
vertices i and j.

Obviously the shortest path between i to j will have some k number of intermediate nodes.
The idea behind floyd warshall algorithm is to treat each and every vertex from 1 to N as an
intermediate node one by one.

The following figure shows the above optimal substructure property in floyd warshall
algorithm:
Floyd Warshall Algorithm Algorithm:
Initialize the solution matrix same as the input graph matrix as a first step.
Then update the solution matrix by considering all vertices as an intermediate vertex.
The idea is to pick all vertices one by one and updates all shortest paths which include
the picked vertex as an intermediate vertex in the shortest path.

When we pick vertex number k as an intermediate vertex, we already have considered


vertices {0, 1, 2, .. k-1} as intermediate vertices.

For every pair (i, j) of the source and destination vertices respectively, there are two
possible cases.

k is not an intermediate vertex in shortest path from i to j. We keep the value of dist[i][j]
as it is.

k is an intermediate vertex in shortest path from i to j. We update the value of dist[i][j] as


dist[i][k] + dist[k][j], if dist[i][j] > dist[i][k] + dist[k][j]
Pseudo-Code of Floyd Warshall Algorithm :

For k = 0 to n – 1
For i = 0 to n – 1
For j = 0 to n – 1
Distance[i, j] = min(Distance[i, j], Distance[i, k] + Distance[k, j])

where i = source Node, j = Destination Node, k = Intermediate Node


Illustration of Floyd Warshall Algorithm :
Suppose we have a graph as shown in the image:
Step 1: Initialize the Distance[][] matrix using the input graph such that Distance[i][j]= weight
of edge from i to j, also Distance[i][j] = Infinity if there is no edge from i to j.
Step 2: Treat node A as an intermediate node and calculate the Distance[][] for every {i,j}
node pair using the formula:

= Distance[i][j] = minimum (Distance[i][j], (Distance from i to A) + (Distance from A to j ))


= Distance[i][j] = minimum (Distance[i][j], Distance[i][A] + Distance[A][j])
Step 3: Treat node B as an intermediate node and calculate the Distance[][] for every {i,j}
node pair using the formula:

= Distance[i][j] = minimum (Distance[i][j], (Distance from i to B) + (Distance from B to j ))


= Distance[i][j] = minimum (Distance[i][j], Distance[i][B] + Distance[B][j])
Step 4: Treat node C as an intermediate node and calculate the Distance[][] for every {i,j}
node pair using the formula:

= Distance[i][j] = minimum (Distance[i][j], (Distance from i to C) + (Distance from C to j ))


= Distance[i][j] = minimum (Distance[i][j], Distance[i][C] + Distance[C][j])
Step 5: Treat node D as an intermediate node and calculate the Distance[][] for every {i,j}
node pair using the formula:

= Distance[i][j] = minimum (Distance[i][j], (Distance from i to D) + (Distance from D to j ))


= Distance[i][j] = minimum (Distance[i][j], Distance[i][D] + Distance[D][j])
Step 6: Treat node E as an intermediate node and calculate the Distance[][] for every {i,j}
node pair using the formula:

= Distance[i][j] = minimum (Distance[i][j], (Distance from i to E) + (Distance from E to j ))


= Distance[i][j] = minimum (Distance[i][j], Distance[i][E] + Distance[E][j])
Step 7: Since all the nodes have been treated as an intermediate node, we can now return
the updated Distance[][] matrix as our answer matrix.

You might also like