0% found this document useful (0 votes)
31 views98 pages

UNIT-5-2

Uploaded by

hitanshuzoz
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)
31 views98 pages

UNIT-5-2

Uploaded by

hitanshuzoz
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/ 98

UNIT-5

SYLLABUS
Graphs and their applications

• Graphs; Linked Representation of Graphs;


Graph Traversal and spanning forests; Depth
first search; Breadth first search.
What is Graph Data Structure?

• A Graph is a non-linear data structure


consisting of vertices and edges.
• The vertices are sometimes also referred to as
nodes and the edges are lines or arcs that
connect any two nodes in the graph.
• More formally a Graph is composed of a set of
vertices( V ) and a set of edges( E ).
• The graph is denoted by G(E, V).
Components of a Graph
Vertices: Vertices are the fundamental units of the graph. Sometimes, vertices
are also known as vertex or nodes. Every node/vertex can be labeled or
unlabelled.
Edges: Edges are drawn or used to connect two nodes of the graph. It can be
ordered pair of nodes in a directed graph. Edges can connect any two nodes in
any possible way. There are no rules. Sometimes, edges are also known as arcs.
Every edge can be labeled/unlabelled.
Graph Terminology
Adjacency: A vertex is said to be adjacent to another vertex if there is an
edge connecting them. Vertices 2 and 3 are not adjacent because there is
no edge between them.
Path: A sequence of edges that allows you to go from vertex A to vertex B
is called a path.
0-1, 1-2 and 0-2 are paths from vertex 0 to vertex 2.
Directed Graph: A graph in which an edge (u,v) doesn't necessarily mean
that there is an edge (v, u) as well. The edges in such a graph are
represented by arrows to show the direction of the edge.
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. The path that starts and finishes at the same vertex is known as a cycle.

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.
Graph Terminology

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 neighbours 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.
– The out-degree of a vertex in a directed graph is the total number of outgoing edges, whereas the in-
degree is the total number of incoming edges.
– A vertex with an in-degree of zero is referred to as a source vertex, while one with an out-degree of
zero is known as sink vertex.
Types of graph

There are two basic types of graph −


• Directed Graph
• Undirected Graph
• Directed graph, as the name suggests, consists
of edges that possess a direction that goes
either away from a vertex or towards the
vertex. Undirected graphs have edges that are
not directed at all.
Example
Example
Types of graph
Graph Operations

The most common graph operations are:


• Check if the element is present in the graph
• Graph Traversal
• Add elements(vertex, edges) to graph
• Finding the path from one vertex to another
• Creating graphs
• Insert vertex
• Delete vertex
• Insert edge
• Delete edge
Graph Representation/Creating Graphs

Two types-
1. Sequential representation (or, Adjacency matrix
representation)
2. Linked list representation (or, Adjacency list
representation)
1. Adjacency Matrix

• An adjacency matrix is a 2D array of V x V


vertices. Each row and column represent a
vertex.
• If the value of any element a[i][j] is 1, it
represents that there is an edge connecting
vertex i and vertex j.
• The adjacency matrix for the graph we created
above is
1. Adjacency Matrix
1. Adjacency Matrix

• Since it is an undirected graph, for edge (0,2), we


also need to mark edge (2,0); making the
adjacency matrix symmetric about the diagonal.

• Edge lookup(checking if an edge exists between


vertex A and vertex B) is extremely fast in
adjacency matrix representation but we have to
reserve space for every possible link between all
vertices(V x V), so it requires more space.
2. Adjacency List

• An adjacency list represents a graph as an


array of linked lists.

• The index of the array represents a vertex and


each element in its linked list represents the
other vertices that form an edge with the
vertex.
An adjacency list is efficient in terms of storage because we only need to store
the values for the edges. For a graph with millions of vertices, this can mean a
lot of saved space.
Example
Insert Vertex

• When you add a vertex that after introducing one or more vertices
or nodes, the graph's size grows by one, increasing the matrix's size
by one at the row and column levels.
Delete Vertex

• Deleting a vertex refers to removing a specific node or vertex from a graph


that has been saved.
• If a removed node appears in the graph, the matrix returns that node. If a
deleted node does not appear in the graph, the matrix returns the node
not available.
Insert Edge

• Connecting two provided vertices can be used to add


an edge to a graph
Delete Edge

• The connection between the vertices or nodes can be


removed to delete an edge.
Graph Traversal Algorithm

• The process of visiting or updating each vertex in a


graph is known as graph traversal. The sequence in
which they visit the vertices is used to classify such
traversals. Graph traversal is a subset of tree traversal.

There are two techniques to implement a graph


traversal algorithm:
• Breadth-first search
• Depth-first search
Breadth-First Search or BFS

• The Breadth First Search (BFS) algorithm is used to search a graph


data structure for a node that meets a set of criteria. It starts at the
root of the graph and visits all nodes at the current depth level
before moving on to the nodes at the next depth level.

• BFS is a search technique for finding a node in a graph data


structure that meets a set of criteria.

• It begins at the root of the graph and investigates all nodes at the
current depth level before moving on to nodes at the next depth
level.

• To maintain track of the child nodes that have been encountered


but not yet inspected, more memory, generally you require
a queue.
Algorithm of breadth-first search

Step 1: Consider the graph you want to navigate.


Step 2: Select any vertex in your graph, say v1, from which you want to
traverse the graph.
Step 3: Examine any two data structures for traversing the graph.
Visited array (size of the graph)
Queue data structure
Step 4: Starting from the vertex, you will add to the visited array, and
afterward, you will v1's adjacent vertices to the queue data
structure.
Step 5: Now, using the FIFO concept, you must remove the element
from the queue, put it into the visited array, and then return to the
queue to add the adjacent vertices of the removed element.
Step 6: Repeat step 5 until the queue is not empty and no vertex is left
to be visited.
BFS algorithm
Step 1: SET STATUS = 1 (ready state) for each node in G
Step 2: Enqueue the starting node A and set its STATUS = 2
(waiting state)
Step 3: Repeat Steps 4 and 5 until QUEUE is empty
Step 4: Dequeue a node N. Process it and set its STATUS = 3
(processed state).
Step 5: Enqueue all the neighbours of N that are in the ready
state (whose STATUS = 1) and set their STATUS = 2 (waiting
state)
[END OF LOOP]
Step 6: EXIT
Example
Example
Depth-First Search or DFS

• DFS is a search technique for finding a node in a graph data structure that meets a set of
criteria.

• Depth First Traversal (or DFS) for a graph is similar to Depth First Traversal of a tree. The only
catch here is, that, unlike trees, graphs may contain cycles (a node may be visited twice). To
avoid processing a node more than once, use a boolean visited array. A graph can have more
than one DFS traversal.

• The depth-first search (DFS) algorithm traverses or explores data structures such as trees and
graphs. The DFS algorithm begins at the root node and examines each branch as far as
feasible before backtracking.

• To maintain track of the child nodes that have been encountered but not yet inspected, more
memory, generally a stack, is required.

• Depth-first search is an algorithm for traversing or searching tree or graph data structures.
The algorithm starts at the root node (selecting some arbitrary node as the root node in the
case of a graph) and explores as far as possible along each branch before backtracking.
Algorithm of depth-first search

Step 1: Consider the graph you want to navigate.


Step 2: Select any vertex in our graph, say v1, from which you want to
begin traversing the graph.
Step 3: Examine any two data structures for traversing the graph.
Visited array (size of the graph)
Stack data structure
Step 4: Insert v1 into the array's first block and push all the adjacent
nodes or vertices of vertex v1 into the stack.
Step 5: Now, using the FIFO principle, pop the topmost element and
put it into the visited array, pushing all of the popped element's
nearby nodes into it.
Step 6: If the topmost element of the stack is already present in the
array, discard it instead of inserting it into the visited array.
Step 7: Repeat step 6 until the stack data structure isn't empty.
Example
Example
Spanning Forest
Spanning forest is a forest that contains every vertex of G such that two vertices are in the
same tree of the forest when there is a path in G between these two vertices.
--> Spanning forest is a forest of spanning tree in the sub-graph of G.
Spanning Tree

• A spanning tree is a subset of an undirected graph that


contains all the vertices of the graph connected with
the minimum number of edges in the graph. Precisely,
the edges of the spanning tree is a subset of the edges
in the original graph.
• If all the vertices are connected in a graph, then there
exists at least one spanning tree. In a graph, there may
exist more than one spanning tree.

Properties
• A spanning tree does not have any cycle.
• Any vertex can be reached from any other vertex.
Example
Minimum Spanning Tree

• A Minimum Spanning Tree (MST) is a subset of edges of a


connected weighted undirected graph that connects all the vertices
together with the minimum possible total edge weight.

• To derive an MST, Prim’s algorithm or Kruskal’s algorithm can be


used.

• One graph may have more than one spanning tree. If there are n
number of vertices, the spanning tree should have − number of
edges. In this context, if each edge of the graph is associated with a
weight and there exists more than one spanning tree, we need to
find the minimum spanning tree of the graph.

• Moreover, if there exist any duplicate weighted edges, the graph


may have multiple minimum spanning tree.
Example
Prim’s algorithm for Minimum Spanning Tree (MST)

• Prim’s algorithm is also a Greedy algorithm.

• This algorithm always starts with a single node and moves through several
adjacent nodes, in order to explore all of the connected edges along the
way.

• Greedy is an algorithmic paradigm that builds up a solution piece by piece,


always choosing the next piece that offers the most obvious and
immediate benefit. Greedy algorithms are used for optimization problems.

• An optimization problem can be solved using Greedy if the problem has the
following property:
– At every step, we can make a choice that looks best at the moment, and we
get the optimal solution to the complete problem.
Prim’s algorithm for Minimum Spanning Tree
(MST)

• The algorithm starts with an empty spanning tree. The idea


is to maintain two sets of vertices.

• The first set contains the vertices already included in the


MST, and the other set contains the vertices not yet
included.

• At every step, it considers all the edges that connect the


two sets and picks the minimum weight edge from these
edges.

• After picking the edge, it moves the other endpoint of the


edge to the set containing MST.
How does Prim’s Algorithm Work?

Step 1: Determine an arbitrary vertex as the starting vertex


of the MST.
Step 2: Follow steps 3 to 5 till there are vertices that are not
included in the MST (known as fringe vertex).
Step 3: Find edges connecting any tree vertex with the
fringe vertices.
Step 4: Find the minimum among these edges.
Step 5: Add the chosen edge to the MST if it does not form
any cycle.
Step 6: Return the MST and exit

Note: For determining a cycle, we can divide the vertices into


two sets [one set contains the vertices included in MST and
the other contains the fringe vertices.]
Example
Kruskal’s Minimum Spanning Tree (MST)
Algorithm

• In Kruskal’s algorithm, sort all edges of the given graph in


increasing order.

• Then it keeps on adding new edges and nodes in the MST if


the newly added edge does not form a cycle.

• It picks the minimum weighted edge at first and the


maximum weighted edge at last.

• Thus we can say that it makes a locally optimal choice in


each step in order to find the optimal solution. Hence this is
a Greedy Algorithm.
How to find MST using Kruskal’s algorithm?

STEP-1: Sort all the edges in non-decreasing order


of their weight.

STEP-2: Pick the smallest edge. Check if it forms a


cycle with the spanning tree formed so far. If the
cycle is not formed, include this edge. Else,
discard it.

STEP-3: Repeat step#2 until there are (V-1) edges in


the spanning tree.
Example
Now pick all edges one by one from the sorted list of edges

• Step 1: Pick edge 7-6. No cycle is formed, include it


Note
• Time and space complexity of Prim’s
algorithm and Kruskal’s algorithm?
• Advantages and disadvantages of Prim’s
algorithm and Kruskal’s algorithm?
Shortest Path

• The shortest path in a graph is defined as the minimum cost route


from one vertex to another. This is most commonly seen in
weighted directed graphs but are also applicable to undirected
graphs.

• A popular real-world application of finding the shortest path in a


graph is a map. Navigation is made easier and simpler with the
various shortest path algorithms where destinations are considered
vertices of the graph and routes are the edges. The two common
shortest path algorithms are −

• Dijkstra’s Shortest Path Algorithm


• Bellman Ford’s Shortest Path Algorithm
Applications of Graph Data Structure

• In Computer science graphs are used to represent the flow of computation.


• Google maps uses graphs for building transportation systems, where intersection of two(or more) roads
are considered to be a vertex and the road connecting two vertices is considered to be an edge, thus their
navigation system is based on the algorithm to calculate the shortest path between two vertices.
• In Facebook, users are considered to be the vertices and if they are friends then there is an edge running
between them. Facebook’s Friend suggestion algorithm uses graph theory. Facebook is an example
of undirected graph.
• In World Wide Web, web pages are considered to be the vertices. There is an edge from a page u to other
page v if there is a link of page v on page u. This is an example of Directed graph. It was the basic idea
behind Google Page Ranking Algorithm.
• In Operating System, we come across the Resource Allocation Graph where each process and resources
are considered to be vertices. Edges are drawn from resources to the allocated process, or from requesting
process to the requested resource. If this leads to any formation of a cycle then a deadlock will occur.
• In mapping system we use graph. It is useful to find out which is an excellent place from the location as
well as your nearby location. In GPS we also use graphs.
• Facebook uses graphs. Using graphs suggests mutual friends. it shows a list of the f following pages,
friends, and contact list.
• Microsoft Excel uses DAG means Directed Acyclic Graphs.
Applications of Graph Data Structure

• In the Dijkstra algorithm, we use a graph. we find the smallest path between two or many nodes.
• On social media sites, we use graphs to track the data of the users. liked showing preferred post
suggestions, recommendations, etc.
• Graphs are used in biochemical applications such as structuring of protein, DNA etc.
• First, analysis to determine structural properties of a network, such as the distribution of vertex degrees
and the diameter of the graph. A vast number of graph measures exist.
• Second, analysis to find a measurable quantity within the network, for example, for a transportation
network, the level of vehicular flow within any portion of it.
• Third, analysis of dynamic properties of network. Map of a country can be represented using a graph. Road
network, Air network or rail network can be represented using a graph. Connection among routers in a
communication network can be represented using a graph. Routing of a packet between two
communicating nodes can be done through the shortest path.
• Graph theory is useful in biology and conservation efforts where a vertex can represent regions where
certain species exist and the edges represent migration paths, or movement between the regions. This
information is important when looking at breeding patterns or tracking the spread of disease.
• Different activities of a project can be represented using a graph. This graph can be useful in project
scheduling.

You might also like