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

Unit 4 Graphs

The document provides an overview of graph theory, defining key concepts such as vertices, edges, types of graphs (directed and undirected), and various graph terminologies. It also discusses graph traversal algorithms like Breadth-First Search (BFS) and Depth-First Search (DFS), as well as minimum spanning tree algorithms including Prim's and Kruskal's. Additionally, Dijkstra's algorithm is introduced for finding the shortest paths in a graph.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Unit 4 Graphs

The document provides an overview of graph theory, defining key concepts such as vertices, edges, types of graphs (directed and undirected), and various graph terminologies. It also discusses graph traversal algorithms like Breadth-First Search (BFS) and Depth-First Search (DFS), as well as minimum spanning tree algorithms including Prim's and Kruskal's. Additionally, Dijkstra's algorithm is introduced for finding the shortest paths in a graph.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 76

Graphs

Introduction
A graph G is defined as an ordered set (V, E), where V(G) represents the set of vertices and E(G)
represents the edges that connect these vertices.

V(G) = {A, B, C, D and E}


E(G) = {(A, B), (B, C), (A, D), (B, D), (D, E),
(C,E)}

Types : Directed Graph and Undirected Graph

In an undirected graph, edges do not have any direction associated with


them.

In a directed graph, edges form an


ordered pair. If there is an edge from A
to B, then there is a path from A to B
but not from B to
A.

The edge (A, B) is said to initiate from


node A (also known as initial node) and
Graph Terminology
Adjacent nodes or neighbors
For every edge, e = (u, v)
that connects nodes u and v,
the nodes u and v are the
end-points and are said to
be the adjacent nodes or
neighbors

Degree of a node Degree of a node u, deg(u),


is the total number of edges containing the
node u. If deg(u) = 0, it means that u does not
belong to any edge and such a node is known
as an isolated node.

Regular graph It is a graph where each vertex has


the same number of neighbors. That is, every node
has the same degree. A regular graph with vertices of
degree k is called a k–regular graph or a regular
graph of degree k.
Path A path P written as P = {v0, v1, v2, ..., vn), of length n from a node
u to v is defined as a sequence of (n+1) nodes. Here, u = v0, v = vn and
vi–1 is adjacent to vi for i = 1, 2, 3, ..., n.

Closed path A path P is known as a closed path if the edge has the same end-points. That
is, if v0 = vn.

Simple path A path P is known as a simple path if all the nodes in the path are distinct.

Cycle A closed simple path with length 3 or more. A cycle of length k is known as k-cycle.

Connected graph A graph is said to be connected if for any two vertices (u, v) in V there is
a path from u to v. That is to say that there are no isolated nodes in a connected graph. A
connected graph that does not have any cycle is called a tree/ free tree/ tree graph .
Complete graph A graph is said to be complete ,
there is an edge between every single pair of the
vertices in the graph. A complete graph is connected.
A complete graph has n(n–1)/2 edges, where n is the
number of nodes in G.
Labelled graph or weighted graph A graph is said
to be labelled if every edge in the graph is
assigned some data. In a weighted graph, the
edges of the graph are assigned some non-
negative weight or length.
Multiple edges Distinct edges which connect the same end-points are
called multiple
edges. That is, e = (u, v) and e' = (u, v) are known as multiple edges of G.
Loop An edge that has identical end-points is called a loop. That is, e = (u,
u). Loop constitute degree 2

Multi-graph A graph with multiple


edges and/or loops is called a
multi-graph.
Size of a graph The size of a graph is
Directed Graphs
A directed graph G, also known as a digraph, is a graph in which every
edge has
a direction assigned to it. An edge of a directed graph is given as an
ordered pair
(u, v) of nodes in G. For an edge (u, v),
• The edge begins at u and terminates at v.
• u is known as the origin or initial point of e. Correspondingly, v is
known as the destination or terminal point of e.
• u is the predecessor of v. Correspondingly, v is the successor of u.
• Nodes u and v are adjacent to each other.
Terminology of a Directed Graph
Out-degree of a node The out-degree of a node u, written as
outdeg(u), is the number of edges that originate at u.
In-degree of a node The in-degree of a node u, written as indeg(u), is the
number of edges that terminate at u.
Degree of a node The degree of a node, written as deg(u), is equal to
the sum of in-degree and out-degree of that node. Therefore, deg(u) =
indeg(u) + outdeg(u).
Isolated vertex A vertex with degree zero. Such a vertex is not an end-
point of any edge.
Pendant vertex (also known as leaf vertex) A vertex with degree one.
Source: A node u is called source if it has positive out degree but zero in degree.
Sink: A node u is called sink if it has positive in degree but zero out degree.

Reachability A node v is said to be reachable from node u, if and only if there exists a
(directed) path from node u to node v.

Strongly connected directed graph A digraph is said to be strongly


connected if and only if there exists a path between every pair of
nodes in G

Unilaterally connected graph A digraph is said to be unilaterally connected


if there exists a path between any pair of nodes u, v in G such that there
is a path from u to v or a path from v to u, but not both.
Weakly connected digraph A directed graph is said to be weakly
connected if it is connected by ignoring the direction of edges.
Parallel/Multiple edges Distinct edges which connect the same end-
points are called multiple edges.
Simple directed graph A directed graph G is said to be a simple directed
graph if and only if it has no parallel edges.

Subgraph: A subgraph G of a graph is graph G' whose vertex set and


edge set
subsets of the graph G
Graph Representation
Graph Traversal
• To analyze a graph, we must first gain access to every
element. This is where traversal algorithms come into
play. These algorithms allow us to traverse a given graph
efficiently and manipulate the data stored within it.
• Depth-First Search (DFS)
• and Breadth-First Search (BFS).
Graph Traversal
1. Breadth-first search
2. Depth-first search
While breadth-first search uses a queue as an auxiliary data structure to store nodes
for further processing, the depth-first search scheme uses a stack. But both these
algorithms make use of a variable STATUS.
BFS
• The full form of BFS is the Breadth-first search.
• The algorithm efficiently visits and marks all the key nodes in a
graph in an accurate breadthwise fashion. This algorithm
selects a single node (initial or source point) in a graph and
then visits all the nodes adjacent to the selected node.
• Remember, BFS accesses these nodes one by one.
• Once the algorithm visits and marks the starting node, then it moves
towards the nearest unvisited nodes and analyses them
• . Once visited, all nodes are marked. These iterations continue until
all the nodes of the graph have been successfully visited and marked.
Breadth First Search Algorithm
• Breadth First Search (BFS) is a graph traversal algorithm that explores all the vertices
of a graph in a breadthward motion, starting from a given source vertex. It uses a
queue data structure to keep track of the vertices that are yet to be explored. The
algorithm works as follows:
• Step 1: Begin by choosing a graph that you want to navigate.
• Step 2: Select a starting vertex from which you want to traverse the graph.
• Step 3: Choose two data structures to use for traversing the graph: a visited array of
size equal to the number of vertices in the graph, and a queue data structure.
• Step 4: Start with the chosen vertex and add it to the visited array. Enqueue all
adjacent vertices of the starting vertex into the queue.
• Step 5: Remove the first vertex from the queue using the FIFO (first-in-first-out)
concept, add it to the visited array, and enqueue all of its unvisited adjacent vertices
into the queue.
• Step 6: Repeat step 5 until the queue is empty and there are no unvisited vertices left
in the graph.
Let us understand the algorithm of breadth first search with the help of an example. Consider

that we will begin the traversal of the following graph from vertex 2 .
For the given graph, there are two different BFS traversals: 2,3,0,1
and 2,0,3,1
• Once, the queue becomes empty, stop the BFS process .
Output of BFS is the order in which elements are
dequeued.
Find path P from A BFS
to I

Time complexity = O(V+E)


Traverse graph using BFS
Depth First Search (DFS)
Algorithm
• Depth First Search (DFS) algorithm is a recursive
algorithm for searching all the vertices of a graph or tree
data structure.
• This algorithm traverses a graph in a depthward motion
and uses a stack to remember to get the next vertex to
start a search, when a dead end occurs in any iteration.
• As in the example given above,
DFS algorithm traverses from S
to A to D to G to E to B first, then
to F and lastly to C. It employs
the following rules.
• Rule 1 − Visit the adjacent
unvisited vertex. Mark it as
visited. Display it. Push it in a
stack.
• Rule 2 − If no adjacent vertex is
found, pop up a vertex from the
stack. (It will pop up all the
vertices from the stack, which do
not have adjacent vertices.)
• Rule 3 − Repeat Rule 1 and
Rule 2 until the stack is empty.
• As C does not have any
unvisited adjacent node so
• The time complexity of the
we keep popping the stack
DFS algorithm is
until we find a node that
represented in the form of
has an unvisited adjacent
O(V + E), where V is the
node.
number of nodes and E is
• In this case, there's none the number of edges.
and we keep popping until
the stack is empty.
• Elements are printed when
we push them on the
stack.

• DFS :S A D B C
DFS
Consider the graph G given in Fig.
13.23. The adjacency list of G is
also given.
Suppose we want to print all the
nodes that can be reached from the
node H (including H itself).

Time complexity = O(V+E)


Minimum spanning tree
A spanning tree of a connected, undirected graph G is a sub-graph of G which is a tree that
connects all the vertices together. A graph G can have many different spanning trees
Prims MST algorithm
Prim’s algorithm is a greedy algorithm that is used to form a minimum
spanning tree for a connected weighted undirected graph.

In other words, the algorithm builds a tree that includes


every vertex and a subset of the edges in such a way that the total
weight of all the edges in the tree
is minimized. For this, the algorithm maintains three sets of vertices
which can be given as below:
Tree vertices Vertices that are a part of the minimum spanning tree T.
Fringe vertices Vertices that are currently not a part of T, but are adjacent
to some tree vertex.
Unseen vertices Vertices that are neither tree vertices nor fringe vertices
fall under
this category.
The steps involved in the Prim’s algorithm are shown in Fig
• Prim’s minimal spanning tree algorithm is one of the efficient
methods to find the minimum spanning tree of a graph.
• A minimum spanning tree is a sub graph that connects all the
vertices present in the main graph with the least possible edges
and minimum cost (sum of the weights assigned to each edge).
• The algorithm, similar to any shortest path algorithm, begins from
a vertex that is set as a root and walks through all the vertices in
the graph by determining the least cost adjacent edges.
Algorithm
• Declare an array visited[] to store the visited vertices and
firstly, add the arbitrary root, say S, to the visited array.
• Check whether the adjacent vertices of the last visited vertex
are present in the visited[] array or not.
• If the vertices are not in the visited[] array, compare the cost of
edges and add the least cost edge to the output spanning tree.
• The adjacent unvisited vertex with the least cost edge is added
into the visited[] array and the least cost edge is added to the
minimum spanning tree output.
• Steps 2 and 4 are repeated for all the unvisited vertices in the
graph to obtain the full minimum spanning tree output for the
given graph.
• Calculate the cost of the minimum spanning tree obtained.
Construct a minimum spanning tree of the graph given in Fig. Start the
Prim’s algorithm from vertex D.
Kruskal’s
algorithm
Kruskal’s algorithm is an example of a greedy algorithm. Kruskal’s algorithm
is used to find the minimum spanning tree for a connected weighted graph.
The algorithm aims to find a subset of the edges that forms a tree that
includes every vertex. The total weight of all the edges in the tree is
minimized

Kruskal’s algorithm sorts all the edges in increasing order of their edge
weights and keeps adding nodes to the tree only if the chosen edge
does not form any cycle.

Also, it picks the edge with a minimum cost at first and the edge with a
maximum cost at last.

Hence, you can say that the Kruskal algorithm makes a locally optimal
choice, intending to find the global optimal solution. That is why it is called a
Greedy Algorithm.
Algo
• Step 1: Sort all edges in increasing order of
their edge weights.
• Step 2: Pick the smallest edge.
• Step 3: Check if the new edge creates a cycle
or loop in a spanning tree.
• Step 4: If it doesn’t form the cycle, then include
that edge in MST. Otherwise, discard it.
• Step 5: Repeat from step 2 until it includes |V| -
1 edges in MST.
Implement Kruskal Algo
1. Proceed with arranging all edges in a sorted list by their
edge weights.
The running time of Kruskal’s and Prims algorithm can be given as
O(E log V), where E is the number of edges and V is the number of
vertices in the graph.
Consider the graph given below.
Find the minimum spanning tree of
this graph using (a) Prim’s
algorithm, (b) Kruskal’s algorithm,
Dijkstra's Algorithm
• Purpose and Use Cases
• With Dijkstra's Algorithm, you can find the shortest path between nodes
in a graph.
• Particularly, you can find the shortest path from a node (called the
"source node") to all other nodes in the graph, producing a shortest-
path tree.
• This algorithm is used in GPS devices to find the shortest path between
the current location and the destination.
• It has broad applications in industry, specially in domains that require
modeling networks.
• Algorithm

Now let’s see the algorithm step by step:
• 1. First of all, we will mark all vertex as unvisited vertex
2. Then, we will mark the source vertex as 0 and all other vertices as infinity
3. Consider source vertex as current vertex
4. Calculate the path length of all the neighboring vertex from the current vertex by adding the
weight of the edge in the current vertex
5. Now, if the new path length is smaller than the previous path length then replace it
otherwise ignore it
6. Mark the current vertex as visited after visiting the neighbor vertex of the current vertex
7. Select the vertex with the smallest path length as the new current vertex and go back to
step 4.
8. Repeat this process until all the vertex are marked as visited.
• Example of Dijkstra's Algorithm
• Now that you know more about this algorithm, let's see how it works
behind the scenes with a a step-by-step example. The algorithm will
generate the shortest path from node 0 to all the other nodes in
the graph.
• 💡 Tip: For this graph, we will assume that the weight of the edges
represents the distance between two nodes.
• Initially, we have this list of distances (please
see the list below):
• The distance from the source node to itself
is 0. For this example, the source node will be
node 0 but it can be any node that you choose.
• The distance from the source node to all other
nodes has not been determined yet, so we use
the infinity symbol to represent this initially.
• We also have this list to keep track of the
nodes that have not been visited yet (nodes
that have not been included in the path)
• Tip: Remember that the algorithm is
completed once all nodes have been added
to the path.
Refer this tutorial
• https://www.freecodecamp.org/news/dijkstras-shortest-
path-algorithm-visual-introduction/
Step 1: We begin with the list of visited vertices empty and all the nodes in the list of
unvisited vertices. The distance from A to A is 0. The shortest distance to all other
vertices is infinity. The current vertex is set to A.
• Step 2: A’s unvisited neighbors are B and
D. The distance to B and D through A
are 0 + 12 = 12 and 0 + 2 = 2
respectively.
• These are shorter than infinity and thus
set to the new shortest distances. A is
added to the list of visited vertices.
• Both distances change; therefore, A is
set to the previous vertex for B and D. D
has the shortest distance and is set
to the next current node.
• Step 3: D’s unvisited neighbors are B and
E. The distance to B and E through D are
2 + 4= 6 and 2 + 2 = 4 respectively.
• The B node distance is changed to 6, and
E’s distance is changed to 4 as both are
lower distances. D is added to the list of
visited vertices and as the previous
vertex for B and E. The new shortest
distance for the D’s neighbors is 4. E is
now the new current node.
• Step 4: E’s
unvisited neighbors
are B and C. The
distance to B and C
through E are 4+
4= 8 and 4+ 10=
14, respectively.
• The distance to C is
changed to 14. E is
added as C’s
previous vertex.
The new shortest
distance for the E’s
neighbors is 6. B is
now the new
current node.
• B’s only remaining
unvisited neighbor is C.
The distance to C
through B is 6+ 10=
16. Nothing is changed.
C is set to the current
node. However, it has
no unvisited vertice
neighbors left, so the
algorithm returns the
table information and
ceases.
Floyd Warshall algorithm
• Shortest path algorithm, similar to Dijkstra’s algorithm
and Bellman ford’s algorithm.
• The only difference is Dijkstra’s and Bellman Ford’s
algorithms are single source shortest path algorithms,
whereas Floyd Warshall is all pair shortest path algorithm,
it can compute the shortest path between every pair of
vertices in the graph.
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]
Now calculating the Distance of
every pair Via A.
Now calculating the Distance of every pair Via B and updating if the
new found weight is lesser than the mentioned weight in the matrix
DB =
Now, calculating distance of each path via C Similarly, if we
calculate the shortest distance Via D, No changes will be
required. and D
• Complexity
• Following are the complexities in the algorithm:
• Time Complexity: There are three for loops in the pseudo-code of the algorithm, so
the time complexity will be O (n^3).
• Space Complexity: The space complexity of Floyd’s Warshall algorithm is O (n^2).
• Application
• In networking devices
• In Routing data packets
• Calculate the inversion of the real matrix
• Calculating transitive closure of directed graphs
Warshall’s Algorithm
END

You might also like