SlideShare a Scribd company logo
Dept of CSE/VEC 1
Dr.M.Usha
Assistant Professor,
Department of CSE
Velammal engineering College
Velammal Engineering College
(An Autonomous Institution, Affiliated to Anna University, Chennai)
(Accredited by NAAC & NBA)
INTRODUCTION TO GRAPH
GRAPH
 A Graph is a non-linear data structure consisting of nodes and edges.
 The nodes are sometimes also referred to as vertices and the edges are lines or arcs
that connect any two nodes in the graph.
 Generally, a graph G is represented as G=(V,E) where V is set of vertices and E is set
of edges.
 In this above Graph, the set of vertices V = {0,1,2,3,4} and the set of edges E = {01,
12, 23, 34, 04, 14, 13}.
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
APPLICATIONS
 Graphs are used to solve many real-life problems.
 Graphs are used to represent networks.
 The networks may include paths in a city or telephone network or circuit
network.
 Graphs are also used in social networks like linkedIn, Facebook.
 For example, in Facebook, each person is represented with a vertex(or node).
 Each node is a structure and contains information like person id, name,
gender, locale etc.
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
TYPES OF GRAPH
 Directed Graph (or) Digraph
 Directed graph is a graph which consists of directed edges, where each edge
in E is unidirectional.
 It is also referred as Digraph. If (v,w) is a directed edge then (v,w) # (w,v)
 Undirected Graph
 An undirected graph is a graph, which consists of undirected edges. If (v,w) is
an undirected edge, then (v,w)=(w,v)
GRAPH TERMINOLOGIES
 A path is a sequence of vertices such that there is an edge
from each vertex to its successor.
 A path is simple if each vertex is distinct/A path with no
repeated vertices is called a simple path.
 A circuit is a path in which the terminal vertex coincides
with the initial vertex.(Vertices may repeat but edges are
not allowed to repeat.)
 Cycle: A circuit that doesn't repeat vertices is called a
cycle.(Neither vertices (except possibly the starting and
ending vertices) are allowed to repeat, Nor edges are
allowed to repeat.
0-1-2-3-0 - CYCLE 0-1-2-4-2-3-0(CIRCUIT)
 Self loop: If there is an edge whose starting and
end vertices are same, that is, (vi, vj) is an edge,
then it is called a self loop.
 Adjacent Vertices
Two vertices are said to be adjacent if there is an
edge (arc) connecting them.
 Adjacent Edges
Adjacent edges are edges that share a common
vertex.
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.
 In degree: Number of edges entering a node
 • Out degree: Number of edges leaving a node
 • Degree = Indegree + Outdegree
Connected and Disconnected
 A graph G is said to be connected if there exists a path between every pair
of vertices.
 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.
 UNCONNECTED/DisConnected GRAPH: A graph is said as unconnected graph
if there exist any 2 unconnected components.
 Example: • H1 and H2 are connected • H3 is disconnected
CONT..
 Weighted Graph
 A graph is said to be weighted graph if every edge in the graph is assigned a weight or
value. It can be directed or undirected graph.
 Complete Graph
 A complete graph is a graph in which there is an direct edge between every pair of
vertices.
 A complete graph with n vertices will have n(n-1)/2 edges.
 There is a path from every vertex to every other vertex.
 All complete graphs are connected graphs, but not all connected graphs are complete
graphs.
 A complete digraph is a strongly connected graph.
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
CONT..
 Strongly Connected Graph
 If there is a path from every vertex to every other vertex in a directed graph
then it is said to be strongly connected graph.
 Weakly Connected Graph:
 If there does not exist a path from one vertex to another vertex then it is said
to be a weakly connected graph.
 Regular Graph
 A graph G is said to be regular, if all its vertices have the same degree. In a
graph, if the degree of each vertex is ‘k’, then the graph is called a ‘k-regular
graph’.
 In the following graphs, all the vertices have the same degree. So these
graphs are called regular graphs.
 In both the graphs, all the vertices have degree 2. They are called 2-Regular
Graphs.
CYCLIC AND ACYCLIC GRPH
 Cyclic Graph
 A graph with at least one cycle is called a cyclic graph.
 Example
 In the above example graph, we have two cycles a-b-c-d-a and c-f-g-e-c.
Hence it is called a cyclic graph
 Acyclic Graph
 A graph with no cycles is called an acyclic graph.
CYCLIC AND ACYCLIC GRPH
 Acyclic Graph
 A directional graph which has no cycles is referred to as acyclic graph. It is
abbreviated as DAG (Directional Acyclic Graph).
 If there is a path containing one or more edges which starts from a vertex vi
and terminates into the same vertex then the path is known as a cycle.
 If a graph(digraph) does not have any cycle then it is called acyclic graph.
GRAPH REPRESENTATION
 Graph data structure is represented using following
representations...
 Adjacency Matrix
 Incidence Matrix
 Adjacency List
ADJACENCY MATRIX
 The adjacency matrix A for a graph G = (V,E) with n vertices, is an n* n matrix
of bits ,
 such that A ij = 1 , if there is an edge from vi to vj and
 Aij = 0, if there is no such edge
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
ADJACENCY LIST
 A graph containing m vertices and n edges can be represented using a linked list, referred
to as adjacency list.
 The number of vertices in a graph forms a singly linked list.
 Each vertex have a separate linked list, with nodes equal to the number of edges connected
from the corresponding vertex..
 Each nodes has at least 2 fields: VERTEX and LINK.
 The VERTEX fields contain the indices of the vertices adjacent to vertex i.
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
Incidence Matrix
 A graph containing m vertices and n edges can be represented by a
matrix with m rows and n columns.
 The matrix formed by storing 1 in the ith row and jth column
corresponding to the matrix, if there exists a ith vertex, connected to
one end of the jth edge, and 0, if there is no ith vertex, connected to
any end of the jth edge of the graph, such a matrix is referred as an
incidence matrix.
 IncMat [i] [j] = 1,if there is an edge Ejfrom vertex Vi
 = 0, otherwise
EXAMPLE
Graph Traversals
 A graph traversal is a systematic way of visiting
the nodes in a specific order.
 There are 2 types of graph traversals namely,
  Breadth First Search(BFS)
  Depth First Search(DFS)
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
Depth first search
 Visit the first node initially, and then find the unvisited
node which is adjacent to the first node, is visited and a
DFS is initiated from the adjacent node (considering it as
the first node).
 If all the adjacent nodes have been visited, backtrack to
the last node visited, and find another adjacent node and
again initiate the DFS from adjacent node.
 This traversal continues until all nodes have been visited
once.
Steps to Implement DFS
 1. Select the start vertex
 2. Visit the vertex ( place 1)
 3. Find the adjacent vertices of visited node
 Rule 1 − Visit any one of 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.
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
EXAMPLE 2:
top
top
top
top
top
top
top
top
top
top
top
top
top
A-B-C-E-D-F-G
EXAMPLE 2
PREORDER TRAVERSAL
S-A-D-G-E-B-F-C
Applications of DFS
  To check whether the undirected graph is connected or
not
  To check if the connected undirected graph is bi-
connected or not
  To check whether the directed graph is a-cyclic or not
BFS (Breadth First Search)
 Breadth First Search (BFS) of a graph G starts from an
unvisited vertex u.
 Then all unvisited vertices vi adjacent to u are visited and
then all unvisited vertices wj adjacent to vi are visited
and so on.
 The traversal terminates when there are no more nodes to
visit.
 BFS uses a queue data structure to keep track of the
order of the nodes whose adjacent nodes are to be
visited.
Steps to Implement BFS
 1. Select the start vertex and mark it as visited (i.e) place the value 1
 2. Enqueue the START vertex.
 3. Dequeue the vertex.
 4. Find all adjacent unvisited vertices of the dequeued vertex.
 5. Mark all unvisited adjacent vertices as visited.
 6. Enqueue all adjacent vertices.
 7. Repeat from step 3 to step 6 until the queue becomes empty
Pseudo Code For BFS
EXAMPLE 2
Front, rear
FRONT REAR
FRONT
REAR
FRONT REAR
FRONT REAR
FRONT REAR
A-D-B-E-C-F-G
Front=1,rear=-1
EXAMPLE 2
LEVEL ORDER TRAVERSAL S-A-B-C-D-E-F-G
Applications of BFS
 1. To find the shortest path from a vertex s to a vertex v in an
unweighted graph
 2. To find the length of such a path
 3. To find out if a graph contains cycles
 4. To construct a BFS tree/forest from a graph
Comparison between DFS and BFS
DFS BFS
DFS visit nodes of graph depth wise. It
visits nodes until reach a leaf or a node
which doesn’t have non-visited nodes.
BFS visit nodes level by level in Graph.
Usually implemented using a stack data
structure.
Usually implemented using a queue data
structure.
Generally requires less memory than BFS. Generally requires more memory than DFS.
Not Optimal for finding the shortest
distance.
optimal for finding the shortest distance.
DFS is better when target is far from
source.
BFS is better when target is closer to
source.
CONT..
DFS BFS
DFS is more suitable for game or puzzle
problems. We make a decision, then
explore all paths through this decision.
And if this decision leads to win
situation, we stop.
BFS considers all neighbors first and
therefore not suitable for decision
making trees used in games or puzzles.
Time Complexity of BFS = O(V+E) where
V is vertices and E is edges.
Time Complexity of DFS is also O(V+E)
where V is vertices and E is edges.
Some Applications:
Finding all connected components in a
graph.
Finding the shortest path between two
nodes.
Finding all nodes within one connected
component.
Testing a graph for bipartiteness.
Some Applications:
Topological Sorting.
Finding connected components.
Solving puzzles such as maze.
Finding strongly connected
components.
Finding articulation points (cut
vertices) of the graph.
TOPOLOGICAL SORTING
 It is a linear ordering of vertices in a directed a-cyclic graph, such that if there is
a path from Vi to Vj, then Vj appears after Vi in the linear ordering.
 Topological sort is not possible if the graph has a cycle.
 Procedure
 1. Find the indegree for every vertex
 2. Place the vertices whose indegree is zero on the empty queue
 3. Dequeue one vertex at a time from the queue and decrement the indegree of
all its adjacent vertices
 4. Enqueue a vertex to the queue if its indegree falls to zero
 5. Repeat from step step 3 unitl the queue becomes empty
 The topological ordering is the order in which the
vertices are dequeued.
Pseudo Code For Topological Sort
EXAMPLE
 Step 1
 Find the Indegree of vertices 1,2,3,4,5,6.
 Indegree of a vertex is the number of edges entering into the vertex. Indegree of
vertex 1 is 0, vertex 2 is 0, vertex 3 is 1, vertex 4 is 3, vertex 5 is 1, vertex 6 is 3.
 Step 2
 enqueue() the vertices with Indegree 0. Therefore enqueue() vertices 1 and 2.
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
Applications:
 Topological Sorting is mainly used for scheduling jobs from the given
dependencies among jobs.
 The jobs are represented by vertices, and there is an edge from x to y if job x
must be completed before job y can be started
 For example, in constructing a building, the basement must be completed
before the first floor, which must be completed before the second floor and
so on.
 A topological sort gives an order in which we should perform the jobs.
 In computer science, applications of this type arise in instruction scheduling,
ordering of formula cell evaluation when recomputing formula values in
spreadsheets,
 Determining the order of compilation tasks to perform in make files
 Data Serialization
Difference Between Tree and Graph
TREE GRAPH
A tree is a special kind of graph that
there are never multiple paths exist.
There is always one way to get from A
to B.
In graph there can be more than one
path i.e graph can have uni-directional
or bi-directional path (edges) between
nodes.
Pre-order, in-order, and post-order are
some kind of the logarithms that are
used in trees to through all elements.
Breath First Search, Depth First Search
are some kind of searching algorithms
in graphs to traverse through each
element.
A tree cannot have a loop structure.
A graph can have a loop structure,
which means the last element and the
first element are same.
There is a unique node called root in
trees.
There is no unique node called root in
graph
Tree is a hierarchical model structure. Graph is network model.
CONT..
All trees are graphs. But all graphs are not trees.
Main use of trees is for sorting and
traversing.
Main use of graphs is coloring and job
scheduling.
Less in complexity compared to graphs. High complexity than trees due to
loops.
Trees are directed acyclic graphs. Graphs are cyclic or acyclic.
Tree contains no loops, no circuits. Graph may contain self-loops, loops.
Tree must be connected. Graph may not be connected.
Dept of CSE/VEC 65
APPLICATION OF GRAPH
OUTLINE
• APPLICATIONS
• MINIMUM SPANNING TREE
– PRIMS ALGORITHM
– KRUSKAL ALGORITHM
• SHORTEST PATH
– DIJIKSTRA ALGORITHM
APPLICATION OF GRAPH
• Graphs are widely used to model any situation
– where entities or things are related to each other in pairs.
– For example, the following information can be represented by
graphs:
– Transportation networks
» In which nodes are airports, ports, etc.
» The edges can be airline flights, shipping routes, etc.
– In maps
» That draw cities/states/regions as vertices and
adjacency relations as edges.
– In circuit networks
» where points of connection are drawn as vertices
and component wires become the edges of the
graph.
Application of Graphs
Google maps
– uses graphs for building transportation systems
– Intersection of two(or more) roads are considered to be a vertex
– Road connecting two vertices is considered to be an edge
– Navigation system is based on the algorithm to calculate the shortest path between two vertices.
Facebook
– Users are considered to be the vertices
– If they are friends then there is an edge running between them.
– undirected graph.
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
– Directed graph.
Operating System
– Resource Allocation Graph
– 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
Minimum Spanning Trees
• 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.
• minimum spanning tree
– is its spanning tree of the smallest weight,
– where the weight of a tree is defined as the sum of the
weights on all its edges.
• The minimum spanning tree problem
– problem of finding a minimum spanning tree for a given
weighted connected graph
Unweighted graph Example
Weighted graph - example
MST - Application
• MSTs are used to find airline routes.
– While the vertices in the graph denote cities, edges
represent the routes between these cities.
– MSTs are used to optimize airline routes by finding
the least costly path with no cycles.
• MSTs are also used to find the cheapest way to connect
terminals, such as cities, electronic components or
computers via roads, airlines, railways, wires or
telephone lines.
• MSTs are applied in routing algorithms for finding the
most efficient path.
Prim’s Algorithm
• Prim’s algorithm is a greedy algorithm
• Used to form a minimum spanning tree for a connected
weighted undirected graph.
• 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.
• 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.
ALGORITHM
//Input: A weighted connected graph G = (V, E)
//Output: T , the set of edges composing a minimum
spanning tree of G
Step 1: Select a starting vertex
Step 2: Repeat Steps 3 and 4 until there are fringe
vertices
Step 3: Select an edge e connecting the tree vertex and
fringe vertex that has minimum weight
Step 4: Add the selected edge and the vertex to the
minimum spanning tree T
[END OF LOOP]
Step 5: EXIT
Example 1
Step-01: Step-02:
Step-03:
Step-04
Example 1
contd..
Step-05: Step-06:
Example 2
Attach two labels to a vertex
• the name of the nearest tree vertex,
• the weight of the corresponding edge.
select a as starting vertex
a(-, -)
b(a, 3)
c(-, ∞)
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
Example 3
KRUSKAL ALGORITHM
Step-01:
Sort all the edges from low weight to high weight.
Step-02:
Take the edge with the lowest weight and use it to connect the vertices of
graph.
If adding an edge creates a cycle, then reject that edge and go for the next
least weight edge.
Step-03:
Keep adding edges until all the vertices are connected and a Minimum
Spanning Tree (MST) is obtained.
Example 1 Step-01
Step-02 Step-03
Step-04 Step-05
Step-06
Step-07
EXAMPLE 2
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
Prims Vs Kruskal
Kruskal’s Algorithm is preferred when
– The graph is sparse.
– There are less number of edges in the graph
– The edges are already sorted or can be sorted in
linear time.
Prim’s Algorithm is preferred when
– The graph is dense.
– There are large number of edges in the graph
Time Complexity
Prims
• If a graph is represented by its weight matrix, then the
running time of Prim’s algorithm is , where n = |V|
• Let graph is represented by its adjacency lists
• Priority queue is implemented as a min-heap
• Running time of Prim’s algorithm is in O(m log n),
– where m = |E|, n = |V|
Kruskal
O(ElogV)
DIJIKSTRA‘S ALGORITHM
• Single-source shortest-path problem
• For a given vertex called the source in a weighted
connected graph
– Find shortest paths to all its other vertices.
– The best-known algorithm for the single-source
shortest-paths problem is called Dijkstra’s
algorithm.
• First, it finds the shortest path from the source to a
vertex nearest to it, then to a second nearest, and so on
DIJIKSTRA ALGORITHM
contd..
 Create a set Tree Vertices that keeps track of vertices included in
shortest path tree
 Initially, this set is empty.
 Assign a distance value to all vertices in the input graph.
 Initialize all distance values as INFINITE.
 Assign distance value as 0 for the source vertex so that it is picked
first.
 While Tree Vertex doesn’t include all vertices
 Pick a vertex u which is not there in Tree Vertex and has minimum
distance value.
 Include u to Tree Vertex.
 Update distance value of all adjacent vertices of u.
For every adjacent vertex v
 if sum of distance value of u (from source) and weight of
edge u-v, is less than the distance value of v
then update the distance value of v.
DIJIKSTRA EXAMPLE
• from a to b : a - b of length 3
• from a to d : a - b - d of length 5
• from a to c : a - b - c of length 7
• from a to e : a - b - d - e of length 9
• Dijikstra’s algorithm does not always work correctly
– If the edge weight is negative.
• The algorithm that is used to solve the negative
weighted, single-source shortest-paths path problem
– Bellman-Ford’s algorithm (using dynamic
programming).
Time Analysis
• Adjacency Matrix Representation
– O(V2
).
• Adjacency list
– O(ElogV)
Dept of CSE/VEC 94
APPLICATION OF GRAPH
&
BICONNECTED GRAPH
OUTLINE
• GRAPH APPLICATIONS
– MINIMUM SPANNING TREE
• PRIMS ALGORITHM
• KRUSKAL ALGORITHM
– SHORTEST PATH
• SINGLE SOURCE- DIJIKSTRA ALGORITHM
• DFS APPLICATION
– BICONNECTED GRAPH
– EULER CIRCUIT
APPLICATION OF GRAPH
• Graphs are widely used to model any situation
– where entities or things are related to each other in
pairs.
– For example, the following information can be
represented by graphs:
– Transportation networks
» In which nodes are airports, ports, etc.
» The edges can be airline flights, shipping
routes, etc.
– In circuit networks
» points of connection are drawn as vertices
» component wires become the edges of the
graph.
Application of Graphs
Google maps
– Intersection of two(or more) roads are considered to be a vertex
– Road connecting two vertices is considered to be an edge
– Navigation system is based on the algorithm to calculate the shortest path between
two vertices.
Facebook
– Users are considered to be the vertices
– If they are friends then there is an edge running between them.
– undirected graph.
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
– Directed graph.
Operating System
– Resource Allocation Graph
– Each process and resources are considered to be vertices.
– Edges are drawn from resources to the allocated process
Minimum Spanning Trees
• A spanning tree of a connected, undirected graph G
– Sub-graph of G which is a tree that connects all the
vertices together.
• A graph G can have many different spanning trees.
• Minimum Spanning Tree
– Spanning tree of the smallest weight
– weight of a tree is defined as the sum of the weights on
all its edges.
• Minimum Spanning Tree problem
– Finding a minimum spanning tree for a given weighted
connected graph
Unweighted graph Example
Weighted graph - example
MST - Application
• MSTs are used to find airline routes.
– Vertices in the graph denote cities
– Edges represent the routes between these cities.
– MSTs are used to optimize airline routes by finding the
least costly path with no cycles.
• MSTs are also used to find the cheapest way to connect
terminals, such as cities, electronic components or
computers via roads, airlines, railways, wires or telephone
lines.
• MSTs are applied in routing algorithms for finding the most
efficient path.
Prim’s Algorithm
• Prim’s algorithm is a greedy algorithm
• Used to form a minimum spanning tree for
a connected weighted undirected graph.
• 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.
• 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.
ALGORITHM
//Input: A weighted connected graph G = (V, E)
//Output: T , the set of edges composing a minimum
spanning tree of G
Step 1: Select a starting vertex
Step 2: Repeat Steps 3 and 4 until there are fringe
vertices
Step 3: Select an edge e connecting the tree vertex
and fringe vertex that has minimum weight
Step 4: Add the selected edge and the vertex to the
minimum spanning tree T
Step 5: EXIT
Example 1
Step-01: Step-02:
Step-03:
Step-04
Example 1
contd..
Step-05: Step-06:
Example 2
Attach two labels to a vertex
• the name of the nearest tree vertex,
• the weight of the corresponding edge.
select a as starting vertex
a(-, -)
b(a, 3)
c(-, ∞)
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
Example 3
Pseudo code
T = ;
∅
U = { 1 };
while (U ≠ V)
let (u, v) be the lowest cost edge such that
u U and v V - U;
∈ ∈
T = T {(u, v)}
∪
U = U {v}
∪
KRUSKAL ALGORITHM
Step-01:
Sort all the edges from low weight to high weight.
Step-02:
Take the edge with the lowest weight and use it to connect the vertices of
graph.
If adding an edge creates a cycle, then reject that edge and go for the next
least weight edge.
Step-03:
Keep adding edges until all the vertices are connected and a Minimum
Spanning Tree (MST) is obtained.
Example 1 Step-01
Step-02 Step-03
Step-04 Step-05
Step-06
Step-07
EXAMPLE 2
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"
Pseudo code
Prims Vs Kruskal
Kruskal’s Algorithm is preferred when
– The graph is sparse.
– There are less number of edges in the graph
– The edges are already sorted or can be sorted in
linear time.
Prim’s Algorithm is preferred when
– The graph is dense.
– There are large number of edges in the graph
Time Complexity
Prims
• If a graph is represented by its weight matrix, then the
running time of Prim’s algorithm is , where n = |V|
• Let graph is represented by its adjacency lists
• Running time of Prim’s algorithm is in O(m log n),
– where m = |E|, n = |V|
Kruskal
O(ElogV)
DIJIKSTRA‘S ALGORITHM
• Single-source shortest-path problem
• For a given vertex called the source in a weighted
connected graph
– Find shortest paths to all its other vertices.
– The best-known algorithm for the single-source
shortest-paths problem is called Dijkstra’s
algorithm.
• First, it finds the shortest path from the source to a
vertex nearest to it, then to a second nearest, and so on
DIJIKSTRA ALGORITHM
contd..
 Create a set Tree Vertices that keeps track of vertices included in
shortest path tree
 Initially, this set is empty.
 Assign a distance value to all vertices in the input graph.
 Initialize all distance values as INFINITE.
 Assign distance value as 0 for the source vertex so that it is picked
first.
 While Tree Vertex doesn’t include all vertices
 Pick a vertex u which is not there in Tree Vertex and has minimum
distance value.
 Include u to Tree Vertex.
 Update distance value of all adjacent vertices of u.
For every adjacent vertex v
 if sum of distance value of u (from source) and weight of
edge u-v, is less than the distance value of v
then update the distance value of v.
DIJIKSTRA EXAMPLE
from a to b : a - b of length 3
from a to d : a - b - d of length 5
from a to c : a - b - c of length 7
from a to e : a - b - d - e of length 9
• Dijikstra’s algorithm does not always work correctly
– If the edge weight is negative.
• The algorithm that is used to solve the negative
weighted, single-source shortest-paths path problem
– Bellman-Ford’s algorithm (using dynamic
programming).
• Time Analysis
– Adjacency Matrix Representation
• O(V2
).
– Adjacency list
• O(ElogV)
Biconnected Graph
• A graph with no articulation point
• If and only if any vertex is deleted, the graph remains
connected
First, starting at any vertex, we perform a depth-
first search and number the nodes as they are
visited.
For each vertex, v, call this preorder number
Num(v)
Low(v) is the minimum of
1. Num(v)
2. the lowest Num(w) among all back edges
(v, w)
3. the lowest Low(w) among all tree edges (v,
w)
Step 1: Find DFN
Step 2: Do Post order Traversal
and Find low value
The root is an articulation point if and only
if it has more than one child
Any other vertex v is an articulation point if
and only if v has some child w such that
Low(w) ≥ Num(v)
Step 3: Rules to find Articulation Point
D has a child E, and Low(E) ≥ Num(D)
C and D are articulation points
C has a child G and Low(G) ≥ Num(C).
Example
Step 1: Find DFN
Step 2: Do Post order Traversal and
Find low value
Ver
tex
0 1 2 3 4 5 6 7 8 9
dfn 4 3 2 0 1 5 6 7 9 8
low 4 0 0 0 0 5 5 5 9 8
the root, vertex 3, is an
articulation point because it has
more than one child.
vertex 1 is an articulation point
since it has a child 0 such that
low (0) ≥ dfn (1)
Vertex 7 is also an articulation
point since low (8) ≥ dfn (7)
vertex 5 is also an articulation
point since low (6) ≥ dfn (5).
Ver
tex
0 1 2 3 4 5 6 7 8 9
dfn 4 3 2 0 1 5 6 7 9 8
low 4 0 0 0 0 5 5 5 9 8
Euler circuit
Eulerian path and circuit for
undirected graph
• Eulerian Path is a path in graph
that visits every edge exactly
once.
• Eulerian Circuit is an Eulerian
Path which starts and ends on the
same vertex.
• An Euler path starts and ends at
different vertices.
• An Euler circuit starts and ends at
the same vertex
• A graph is called Eulerian if it has
an Eulerian Cycle and called
Semi-Eulerian if it has an Eulerian
Path
Euler Path Eg
Euler Path to exist in a graph, exactly 0 or 2 vertices must have odd degree
Start with one of the odd vertices. End in the other one
Euler Circuit
All vertices must have even degree
Condition for Euler Path and Euler Circuit
DFS to find Euler circuit
2 , 1, 0, 2
2, 1,0, 3,4,0,2
 Start with any vertex s.
 First, using DFS find any circuit
starting and ending in s.
 Mark all edges on the circuit as
visited
 While there are still edges in the
graph that are not marked
visited:
• Find the first vertex v on
the circuit that has unvisited
edges.
• Find a circuit starting in v
and splice this path into the first
circuit
1,0,2,1
1,0,3,4,0,2,1
Solution 1
Solution 2
QUESTIONS
THANK YOU

More Related Content

PPTX
UNIT IV NON LINEAR DATA STRUCTURES - GRAPH.pptx
PPTX
UNIT IV NON LINEAR DATA STRUCTURES - GRAPH
PPTX
UNIT III.pptx
PPTX
logic.pptx
PPTX
DATA STRUCTURES.pptx
PPT
Data Structures-Non Linear DataStructures-Graphs
PPTX
UNIT IV NON LINEAR DATA STRUCTURES - GRAPH.pptx
UNIT IV NON LINEAR DATA STRUCTURES - GRAPH
UNIT III.pptx
logic.pptx
DATA STRUCTURES.pptx
Data Structures-Non Linear DataStructures-Graphs

Similar to Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science" (20)

PPTX
Graph data structures for ppt for understanding.pptx
PDF
Unit-10 Graphs .pdf
PPTX
Data Structure of computer science and technology
PPTX
Graph in data structure
PPSX
Unit-6 Graph.ppsx ppt
PPTX
PPTX
Graph Data Structure Concepts with Types, Representations, Traversal Techniqu...
PDF
unit-3-dsa-graph introduction to grapgh and graph type
PDF
Graphhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh.pdf
PPTX
Unit II_Graph.pptxkgjrekjgiojtoiejhgnltegjte
PPTX
NON-LINEAR DATA STRUCTURE-Graphs.pptx
PPT
Lecture 5b graphs and hashing
PDF
Daa chpater 12
PPTX
Spanningtreesppt
PPTX
UNIT II - Graph Algorithms techniques.pptx
PDF
LEC 12-DSALGO-GRAPHS(final12).pdf
PPT
14. GRAPH in data structures and algorithm.ppt
PPTX
Depth first traversal(data structure algorithms)
PPTX
Lecture 2.3.1 Graph.pptx
PPTX
Graph terminology and algorithm and tree.pptx
Graph data structures for ppt for understanding.pptx
Unit-10 Graphs .pdf
Data Structure of computer science and technology
Graph in data structure
Unit-6 Graph.ppsx ppt
Graph Data Structure Concepts with Types, Representations, Traversal Techniqu...
unit-3-dsa-graph introduction to grapgh and graph type
Graphhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh.pdf
Unit II_Graph.pptxkgjrekjgiojtoiejhgnltegjte
NON-LINEAR DATA STRUCTURE-Graphs.pptx
Lecture 5b graphs and hashing
Daa chpater 12
Spanningtreesppt
UNIT II - Graph Algorithms techniques.pptx
LEC 12-DSALGO-GRAPHS(final12).pdf
14. GRAPH in data structures and algorithm.ppt
Depth first traversal(data structure algorithms)
Lecture 2.3.1 Graph.pptx
Graph terminology and algorithm and tree.pptx
Ad

More from usham61 (13)

PPTX
Tree Data Structures with Types, Properties, Traversals, Advanced Variants, a...
PPTX
tack Data Structure with Array and Linked List Implementation, Push and Pop O...
PPTX
"Array and Linked List in Data Structures with Types, Operations, Implementat...
PPTX
Sorting and Hashing in Data Structures with Algorithms, Techniques, Implement...
PPTX
Application of graph ,biconnectivity FDP on DS.pptx
PPTX
Real-Life Applications of Graph Data Structures in Networks, Social Media, Sh...
PPTX
AVL Tree Data Structure with Insertion, Deletion, Rotations, Balancing Techni...
PPTX
B Tree Data Structure Concepts with Insertion, Deletion, Searching, and Appli...
PPTX
Tree Traversal Techniques in Data Structures with Inorder, Preorder, Postorde...
PPT
AVL Tree Animation with Rotations, Balancing Techniques, and Step-by-Step Ope...
PPTX
Comprehensive Guide to Queue Data Structure with Operations, Types, and Appli...
PPTX
Introduction to Arrays and Linked Lists with Operations, Types, and Applicati...
PPTX
Stack Data Structure Explained with Array and Linked List Implementation, Ope...
Tree Data Structures with Types, Properties, Traversals, Advanced Variants, a...
tack Data Structure with Array and Linked List Implementation, Push and Pop O...
"Array and Linked List in Data Structures with Types, Operations, Implementat...
Sorting and Hashing in Data Structures with Algorithms, Techniques, Implement...
Application of graph ,biconnectivity FDP on DS.pptx
Real-Life Applications of Graph Data Structures in Networks, Social Media, Sh...
AVL Tree Data Structure with Insertion, Deletion, Rotations, Balancing Techni...
B Tree Data Structure Concepts with Insertion, Deletion, Searching, and Appli...
Tree Traversal Techniques in Data Structures with Inorder, Preorder, Postorde...
AVL Tree Animation with Rotations, Balancing Techniques, and Step-by-Step Ope...
Comprehensive Guide to Queue Data Structure with Operations, Types, and Appli...
Introduction to Arrays and Linked Lists with Operations, Types, and Applicati...
Stack Data Structure Explained with Array and Linked List Implementation, Ope...
Ad

Recently uploaded (20)

PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PDF
Visual Aids for Exploratory Data Analysis.pdf
PPT
Occupational Health and Safety Management System
PDF
PREDICTION OF DIABETES FROM ELECTRONIC HEALTH RECORDS
PDF
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
PDF
EXPLORING LEARNING ENGAGEMENT FACTORS INFLUENCING BEHAVIORAL, COGNITIVE, AND ...
PDF
Exploratory_Data_Analysis_Fundamentals.pdf
PPTX
Module 8- Technological and Communication Skills.pptx
PPTX
AUTOMOTIVE ENGINE MANAGEMENT (MECHATRONICS).pptx
PDF
August 2025 - Top 10 Read Articles in Network Security & Its Applications
PDF
737-MAX_SRG.pdf student reference guides
PPTX
Fundamentals of Mechanical Engineering.pptx
PDF
Abrasive, erosive and cavitation wear.pdf
PDF
Soil Improvement Techniques Note - Rabbi
PDF
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
PDF
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
PDF
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PDF
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF
PPTX
Information Storage and Retrieval Techniques Unit III
Automation-in-Manufacturing-Chapter-Introduction.pdf
Visual Aids for Exploratory Data Analysis.pdf
Occupational Health and Safety Management System
PREDICTION OF DIABETES FROM ELECTRONIC HEALTH RECORDS
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
EXPLORING LEARNING ENGAGEMENT FACTORS INFLUENCING BEHAVIORAL, COGNITIVE, AND ...
Exploratory_Data_Analysis_Fundamentals.pdf
Module 8- Technological and Communication Skills.pptx
AUTOMOTIVE ENGINE MANAGEMENT (MECHATRONICS).pptx
August 2025 - Top 10 Read Articles in Network Security & Its Applications
737-MAX_SRG.pdf student reference guides
Fundamentals of Mechanical Engineering.pptx
Abrasive, erosive and cavitation wear.pdf
Soil Improvement Techniques Note - Rabbi
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
R24 SURVEYING LAB MANUAL for civil enggi
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF
Information Storage and Retrieval Techniques Unit III

Graph Data Structures with Types, Traversals, Connectivity, and Real-Life Applications in Computer Science"

  • 1. Dept of CSE/VEC 1 Dr.M.Usha Assistant Professor, Department of CSE Velammal engineering College Velammal Engineering College (An Autonomous Institution, Affiliated to Anna University, Chennai) (Accredited by NAAC & NBA) INTRODUCTION TO GRAPH
  • 2. GRAPH  A Graph is a non-linear data structure consisting of nodes and edges.  The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph.  Generally, a graph G is represented as G=(V,E) where V is set of vertices and E is set of edges.  In this above Graph, the set of vertices V = {0,1,2,3,4} and the set of edges E = {01, 12, 23, 34, 04, 14, 13}.
  • 4. APPLICATIONS  Graphs are used to solve many real-life problems.  Graphs are used to represent networks.  The networks may include paths in a city or telephone network or circuit network.  Graphs are also used in social networks like linkedIn, Facebook.  For example, in Facebook, each person is represented with a vertex(or node).  Each node is a structure and contains information like person id, name, gender, locale etc.
  • 9. TYPES OF GRAPH  Directed Graph (or) Digraph  Directed graph is a graph which consists of directed edges, where each edge in E is unidirectional.  It is also referred as Digraph. If (v,w) is a directed edge then (v,w) # (w,v)  Undirected Graph  An undirected graph is a graph, which consists of undirected edges. If (v,w) is an undirected edge, then (v,w)=(w,v)
  • 10. GRAPH TERMINOLOGIES  A path is a sequence of vertices such that there is an edge from each vertex to its successor.  A path is simple if each vertex is distinct/A path with no repeated vertices is called a simple path.  A circuit is a path in which the terminal vertex coincides with the initial vertex.(Vertices may repeat but edges are not allowed to repeat.)  Cycle: A circuit that doesn't repeat vertices is called a cycle.(Neither vertices (except possibly the starting and ending vertices) are allowed to repeat, Nor edges are allowed to repeat. 0-1-2-3-0 - CYCLE 0-1-2-4-2-3-0(CIRCUIT)
  • 11.  Self loop: If there is an edge whose starting and end vertices are same, that is, (vi, vj) is an edge, then it is called a self loop.  Adjacent Vertices Two vertices are said to be adjacent if there is an edge (arc) connecting them.  Adjacent Edges Adjacent edges are edges that share a common vertex.
  • 12. 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.  In degree: Number of edges entering a node  • Out degree: Number of edges leaving a node  • Degree = Indegree + Outdegree
  • 13. Connected and Disconnected  A graph G is said to be connected if there exists a path between every pair of vertices.  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.  UNCONNECTED/DisConnected GRAPH: A graph is said as unconnected graph if there exist any 2 unconnected components.  Example: • H1 and H2 are connected • H3 is disconnected
  • 14. CONT..  Weighted Graph  A graph is said to be weighted graph if every edge in the graph is assigned a weight or value. It can be directed or undirected graph.  Complete Graph  A complete graph is a graph in which there is an direct edge between every pair of vertices.  A complete graph with n vertices will have n(n-1)/2 edges.  There is a path from every vertex to every other vertex.  All complete graphs are connected graphs, but not all connected graphs are complete graphs.  A complete digraph is a strongly connected graph.
  • 16. CONT..  Strongly Connected Graph  If there is a path from every vertex to every other vertex in a directed graph then it is said to be strongly connected graph.  Weakly Connected Graph:  If there does not exist a path from one vertex to another vertex then it is said to be a weakly connected graph.
  • 17.  Regular Graph  A graph G is said to be regular, if all its vertices have the same degree. In a graph, if the degree of each vertex is ‘k’, then the graph is called a ‘k-regular graph’.  In the following graphs, all the vertices have the same degree. So these graphs are called regular graphs.  In both the graphs, all the vertices have degree 2. They are called 2-Regular Graphs.
  • 18. CYCLIC AND ACYCLIC GRPH  Cyclic Graph  A graph with at least one cycle is called a cyclic graph.  Example  In the above example graph, we have two cycles a-b-c-d-a and c-f-g-e-c. Hence it is called a cyclic graph  Acyclic Graph  A graph with no cycles is called an acyclic graph.
  • 19. CYCLIC AND ACYCLIC GRPH  Acyclic Graph  A directional graph which has no cycles is referred to as acyclic graph. It is abbreviated as DAG (Directional Acyclic Graph).  If there is a path containing one or more edges which starts from a vertex vi and terminates into the same vertex then the path is known as a cycle.  If a graph(digraph) does not have any cycle then it is called acyclic graph.
  • 20. GRAPH REPRESENTATION  Graph data structure is represented using following representations...  Adjacency Matrix  Incidence Matrix  Adjacency List
  • 21. ADJACENCY MATRIX  The adjacency matrix A for a graph G = (V,E) with n vertices, is an n* n matrix of bits ,  such that A ij = 1 , if there is an edge from vi to vj and  Aij = 0, if there is no such edge
  • 23. ADJACENCY LIST  A graph containing m vertices and n edges can be represented using a linked list, referred to as adjacency list.  The number of vertices in a graph forms a singly linked list.  Each vertex have a separate linked list, with nodes equal to the number of edges connected from the corresponding vertex..  Each nodes has at least 2 fields: VERTEX and LINK.  The VERTEX fields contain the indices of the vertices adjacent to vertex i.
  • 25. Incidence Matrix  A graph containing m vertices and n edges can be represented by a matrix with m rows and n columns.  The matrix formed by storing 1 in the ith row and jth column corresponding to the matrix, if there exists a ith vertex, connected to one end of the jth edge, and 0, if there is no ith vertex, connected to any end of the jth edge of the graph, such a matrix is referred as an incidence matrix.  IncMat [i] [j] = 1,if there is an edge Ejfrom vertex Vi  = 0, otherwise
  • 27. Graph Traversals  A graph traversal is a systematic way of visiting the nodes in a specific order.  There are 2 types of graph traversals namely,   Breadth First Search(BFS)   Depth First Search(DFS)
  • 29. Depth first search  Visit the first node initially, and then find the unvisited node which is adjacent to the first node, is visited and a DFS is initiated from the adjacent node (considering it as the first node).  If all the adjacent nodes have been visited, backtrack to the last node visited, and find another adjacent node and again initiate the DFS from adjacent node.  This traversal continues until all nodes have been visited once.
  • 30. Steps to Implement DFS  1. Select the start vertex  2. Visit the vertex ( place 1)  3. Find the adjacent vertices of visited node  Rule 1 − Visit any one of 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.
  • 41. Applications of DFS   To check whether the undirected graph is connected or not   To check if the connected undirected graph is bi- connected or not   To check whether the directed graph is a-cyclic or not
  • 42. BFS (Breadth First Search)  Breadth First Search (BFS) of a graph G starts from an unvisited vertex u.  Then all unvisited vertices vi adjacent to u are visited and then all unvisited vertices wj adjacent to vi are visited and so on.  The traversal terminates when there are no more nodes to visit.  BFS uses a queue data structure to keep track of the order of the nodes whose adjacent nodes are to be visited.
  • 43. Steps to Implement BFS  1. Select the start vertex and mark it as visited (i.e) place the value 1  2. Enqueue the START vertex.  3. Dequeue the vertex.  4. Find all adjacent unvisited vertices of the dequeued vertex.  5. Mark all unvisited adjacent vertices as visited.  6. Enqueue all adjacent vertices.  7. Repeat from step 3 to step 6 until the queue becomes empty
  • 50. EXAMPLE 2 LEVEL ORDER TRAVERSAL S-A-B-C-D-E-F-G
  • 51. Applications of BFS  1. To find the shortest path from a vertex s to a vertex v in an unweighted graph  2. To find the length of such a path  3. To find out if a graph contains cycles  4. To construct a BFS tree/forest from a graph
  • 52. Comparison between DFS and BFS DFS BFS DFS visit nodes of graph depth wise. It visits nodes until reach a leaf or a node which doesn’t have non-visited nodes. BFS visit nodes level by level in Graph. Usually implemented using a stack data structure. Usually implemented using a queue data structure. Generally requires less memory than BFS. Generally requires more memory than DFS. Not Optimal for finding the shortest distance. optimal for finding the shortest distance. DFS is better when target is far from source. BFS is better when target is closer to source.
  • 53. CONT.. DFS BFS DFS is more suitable for game or puzzle problems. We make a decision, then explore all paths through this decision. And if this decision leads to win situation, we stop. BFS considers all neighbors first and therefore not suitable for decision making trees used in games or puzzles. Time Complexity of BFS = O(V+E) where V is vertices and E is edges. Time Complexity of DFS is also O(V+E) where V is vertices and E is edges. Some Applications: Finding all connected components in a graph. Finding the shortest path between two nodes. Finding all nodes within one connected component. Testing a graph for bipartiteness. Some Applications: Topological Sorting. Finding connected components. Solving puzzles such as maze. Finding strongly connected components. Finding articulation points (cut vertices) of the graph.
  • 54. TOPOLOGICAL SORTING  It is a linear ordering of vertices in a directed a-cyclic graph, such that if there is a path from Vi to Vj, then Vj appears after Vi in the linear ordering.  Topological sort is not possible if the graph has a cycle.  Procedure  1. Find the indegree for every vertex  2. Place the vertices whose indegree is zero on the empty queue  3. Dequeue one vertex at a time from the queue and decrement the indegree of all its adjacent vertices  4. Enqueue a vertex to the queue if its indegree falls to zero  5. Repeat from step step 3 unitl the queue becomes empty  The topological ordering is the order in which the vertices are dequeued.
  • 55. Pseudo Code For Topological Sort
  • 56. EXAMPLE  Step 1  Find the Indegree of vertices 1,2,3,4,5,6.  Indegree of a vertex is the number of edges entering into the vertex. Indegree of vertex 1 is 0, vertex 2 is 0, vertex 3 is 1, vertex 4 is 3, vertex 5 is 1, vertex 6 is 3.  Step 2  enqueue() the vertices with Indegree 0. Therefore enqueue() vertices 1 and 2.
  • 62. Applications:  Topological Sorting is mainly used for scheduling jobs from the given dependencies among jobs.  The jobs are represented by vertices, and there is an edge from x to y if job x must be completed before job y can be started  For example, in constructing a building, the basement must be completed before the first floor, which must be completed before the second floor and so on.  A topological sort gives an order in which we should perform the jobs.  In computer science, applications of this type arise in instruction scheduling, ordering of formula cell evaluation when recomputing formula values in spreadsheets,  Determining the order of compilation tasks to perform in make files  Data Serialization
  • 63. Difference Between Tree and Graph TREE GRAPH A tree is a special kind of graph that there are never multiple paths exist. There is always one way to get from A to B. In graph there can be more than one path i.e graph can have uni-directional or bi-directional path (edges) between nodes. Pre-order, in-order, and post-order are some kind of the logarithms that are used in trees to through all elements. Breath First Search, Depth First Search are some kind of searching algorithms in graphs to traverse through each element. A tree cannot have a loop structure. A graph can have a loop structure, which means the last element and the first element are same. There is a unique node called root in trees. There is no unique node called root in graph Tree is a hierarchical model structure. Graph is network model.
  • 64. CONT.. All trees are graphs. But all graphs are not trees. Main use of trees is for sorting and traversing. Main use of graphs is coloring and job scheduling. Less in complexity compared to graphs. High complexity than trees due to loops. Trees are directed acyclic graphs. Graphs are cyclic or acyclic. Tree contains no loops, no circuits. Graph may contain self-loops, loops. Tree must be connected. Graph may not be connected.
  • 65. Dept of CSE/VEC 65 APPLICATION OF GRAPH
  • 66. OUTLINE • APPLICATIONS • MINIMUM SPANNING TREE – PRIMS ALGORITHM – KRUSKAL ALGORITHM • SHORTEST PATH – DIJIKSTRA ALGORITHM
  • 67. APPLICATION OF GRAPH • Graphs are widely used to model any situation – where entities or things are related to each other in pairs. – For example, the following information can be represented by graphs: – Transportation networks » In which nodes are airports, ports, etc. » The edges can be airline flights, shipping routes, etc. – In maps » That draw cities/states/regions as vertices and adjacency relations as edges. – In circuit networks » where points of connection are drawn as vertices and component wires become the edges of the graph.
  • 68. Application of Graphs Google maps – uses graphs for building transportation systems – Intersection of two(or more) roads are considered to be a vertex – Road connecting two vertices is considered to be an edge – Navigation system is based on the algorithm to calculate the shortest path between two vertices. Facebook – Users are considered to be the vertices – If they are friends then there is an edge running between them. – undirected graph. 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 – Directed graph. Operating System – Resource Allocation Graph – 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
  • 69. Minimum Spanning Trees • 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. • minimum spanning tree – is its spanning tree of the smallest weight, – where the weight of a tree is defined as the sum of the weights on all its edges. • The minimum spanning tree problem – problem of finding a minimum spanning tree for a given weighted connected graph
  • 71. Weighted graph - example
  • 72. MST - Application • MSTs are used to find airline routes. – While the vertices in the graph denote cities, edges represent the routes between these cities. – MSTs are used to optimize airline routes by finding the least costly path with no cycles. • MSTs are also used to find the cheapest way to connect terminals, such as cities, electronic components or computers via roads, airlines, railways, wires or telephone lines. • MSTs are applied in routing algorithms for finding the most efficient path.
  • 73. Prim’s Algorithm • Prim’s algorithm is a greedy algorithm • Used to form a minimum spanning tree for a connected weighted undirected graph. • 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. • 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.
  • 74. ALGORITHM //Input: A weighted connected graph G = (V, E) //Output: T , the set of edges composing a minimum spanning tree of G Step 1: Select a starting vertex Step 2: Repeat Steps 3 and 4 until there are fringe vertices Step 3: Select an edge e connecting the tree vertex and fringe vertex that has minimum weight Step 4: Add the selected edge and the vertex to the minimum spanning tree T [END OF LOOP] Step 5: EXIT
  • 77. Example 2 Attach two labels to a vertex • the name of the nearest tree vertex, • the weight of the corresponding edge. select a as starting vertex a(-, -) b(a, 3) c(-, ∞)
  • 82. KRUSKAL ALGORITHM Step-01: Sort all the edges from low weight to high weight. Step-02: Take the edge with the lowest weight and use it to connect the vertices of graph. If adding an edge creates a cycle, then reject that edge and go for the next least weight edge. Step-03: Keep adding edges until all the vertices are connected and a Minimum Spanning Tree (MST) is obtained.
  • 87. Prims Vs Kruskal Kruskal’s Algorithm is preferred when – The graph is sparse. – There are less number of edges in the graph – The edges are already sorted or can be sorted in linear time. Prim’s Algorithm is preferred when – The graph is dense. – There are large number of edges in the graph
  • 88. Time Complexity Prims • If a graph is represented by its weight matrix, then the running time of Prim’s algorithm is , where n = |V| • Let graph is represented by its adjacency lists • Priority queue is implemented as a min-heap • Running time of Prim’s algorithm is in O(m log n), – where m = |E|, n = |V| Kruskal O(ElogV)
  • 89. DIJIKSTRA‘S ALGORITHM • Single-source shortest-path problem • For a given vertex called the source in a weighted connected graph – Find shortest paths to all its other vertices. – The best-known algorithm for the single-source shortest-paths problem is called Dijkstra’s algorithm. • First, it finds the shortest path from the source to a vertex nearest to it, then to a second nearest, and so on
  • 90. DIJIKSTRA ALGORITHM contd..  Create a set Tree Vertices that keeps track of vertices included in shortest path tree  Initially, this set is empty.  Assign a distance value to all vertices in the input graph.  Initialize all distance values as INFINITE.  Assign distance value as 0 for the source vertex so that it is picked first.  While Tree Vertex doesn’t include all vertices  Pick a vertex u which is not there in Tree Vertex and has minimum distance value.  Include u to Tree Vertex.  Update distance value of all adjacent vertices of u. For every adjacent vertex v  if sum of distance value of u (from source) and weight of edge u-v, is less than the distance value of v then update the distance value of v.
  • 92. • from a to b : a - b of length 3 • from a to d : a - b - d of length 5 • from a to c : a - b - c of length 7 • from a to e : a - b - d - e of length 9 • Dijikstra’s algorithm does not always work correctly – If the edge weight is negative. • The algorithm that is used to solve the negative weighted, single-source shortest-paths path problem – Bellman-Ford’s algorithm (using dynamic programming).
  • 93. Time Analysis • Adjacency Matrix Representation – O(V2 ). • Adjacency list – O(ElogV)
  • 94. Dept of CSE/VEC 94 APPLICATION OF GRAPH & BICONNECTED GRAPH
  • 95. OUTLINE • GRAPH APPLICATIONS – MINIMUM SPANNING TREE • PRIMS ALGORITHM • KRUSKAL ALGORITHM – SHORTEST PATH • SINGLE SOURCE- DIJIKSTRA ALGORITHM • DFS APPLICATION – BICONNECTED GRAPH – EULER CIRCUIT
  • 96. APPLICATION OF GRAPH • Graphs are widely used to model any situation – where entities or things are related to each other in pairs. – For example, the following information can be represented by graphs: – Transportation networks » In which nodes are airports, ports, etc. » The edges can be airline flights, shipping routes, etc. – In circuit networks » points of connection are drawn as vertices » component wires become the edges of the graph.
  • 97. Application of Graphs Google maps – Intersection of two(or more) roads are considered to be a vertex – Road connecting two vertices is considered to be an edge – Navigation system is based on the algorithm to calculate the shortest path between two vertices. Facebook – Users are considered to be the vertices – If they are friends then there is an edge running between them. – undirected graph. 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 – Directed graph. Operating System – Resource Allocation Graph – Each process and resources are considered to be vertices. – Edges are drawn from resources to the allocated process
  • 98. Minimum Spanning Trees • A spanning tree of a connected, undirected graph G – Sub-graph of G which is a tree that connects all the vertices together. • A graph G can have many different spanning trees. • Minimum Spanning Tree – Spanning tree of the smallest weight – weight of a tree is defined as the sum of the weights on all its edges. • Minimum Spanning Tree problem – Finding a minimum spanning tree for a given weighted connected graph
  • 100. Weighted graph - example
  • 101. MST - Application • MSTs are used to find airline routes. – Vertices in the graph denote cities – Edges represent the routes between these cities. – MSTs are used to optimize airline routes by finding the least costly path with no cycles. • MSTs are also used to find the cheapest way to connect terminals, such as cities, electronic components or computers via roads, airlines, railways, wires or telephone lines. • MSTs are applied in routing algorithms for finding the most efficient path.
  • 102. Prim’s Algorithm • Prim’s algorithm is a greedy algorithm • Used to form a minimum spanning tree for a connected weighted undirected graph. • 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. • 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.
  • 103. ALGORITHM //Input: A weighted connected graph G = (V, E) //Output: T , the set of edges composing a minimum spanning tree of G Step 1: Select a starting vertex Step 2: Repeat Steps 3 and 4 until there are fringe vertices Step 3: Select an edge e connecting the tree vertex and fringe vertex that has minimum weight Step 4: Add the selected edge and the vertex to the minimum spanning tree T Step 5: EXIT
  • 106. Example 2 Attach two labels to a vertex • the name of the nearest tree vertex, • the weight of the corresponding edge. select a as starting vertex a(-, -) b(a, 3) c(-, ∞)
  • 111. Pseudo code T = ; ∅ U = { 1 }; while (U ≠ V) let (u, v) be the lowest cost edge such that u U and v V - U; ∈ ∈ T = T {(u, v)} ∪ U = U {v} ∪
  • 112. KRUSKAL ALGORITHM Step-01: Sort all the edges from low weight to high weight. Step-02: Take the edge with the lowest weight and use it to connect the vertices of graph. If adding an edge creates a cycle, then reject that edge and go for the next least weight edge. Step-03: Keep adding edges until all the vertices are connected and a Minimum Spanning Tree (MST) is obtained.
  • 119. Prims Vs Kruskal Kruskal’s Algorithm is preferred when – The graph is sparse. – There are less number of edges in the graph – The edges are already sorted or can be sorted in linear time. Prim’s Algorithm is preferred when – The graph is dense. – There are large number of edges in the graph
  • 120. Time Complexity Prims • If a graph is represented by its weight matrix, then the running time of Prim’s algorithm is , where n = |V| • Let graph is represented by its adjacency lists • Running time of Prim’s algorithm is in O(m log n), – where m = |E|, n = |V| Kruskal O(ElogV)
  • 121. DIJIKSTRA‘S ALGORITHM • Single-source shortest-path problem • For a given vertex called the source in a weighted connected graph – Find shortest paths to all its other vertices. – The best-known algorithm for the single-source shortest-paths problem is called Dijkstra’s algorithm. • First, it finds the shortest path from the source to a vertex nearest to it, then to a second nearest, and so on
  • 122. DIJIKSTRA ALGORITHM contd..  Create a set Tree Vertices that keeps track of vertices included in shortest path tree  Initially, this set is empty.  Assign a distance value to all vertices in the input graph.  Initialize all distance values as INFINITE.  Assign distance value as 0 for the source vertex so that it is picked first.  While Tree Vertex doesn’t include all vertices  Pick a vertex u which is not there in Tree Vertex and has minimum distance value.  Include u to Tree Vertex.  Update distance value of all adjacent vertices of u. For every adjacent vertex v  if sum of distance value of u (from source) and weight of edge u-v, is less than the distance value of v then update the distance value of v.
  • 124. from a to b : a - b of length 3 from a to d : a - b - d of length 5 from a to c : a - b - c of length 7 from a to e : a - b - d - e of length 9
  • 125. • Dijikstra’s algorithm does not always work correctly – If the edge weight is negative. • The algorithm that is used to solve the negative weighted, single-source shortest-paths path problem – Bellman-Ford’s algorithm (using dynamic programming). • Time Analysis – Adjacency Matrix Representation • O(V2 ). – Adjacency list • O(ElogV)
  • 126. Biconnected Graph • A graph with no articulation point • If and only if any vertex is deleted, the graph remains connected
  • 127. First, starting at any vertex, we perform a depth- first search and number the nodes as they are visited. For each vertex, v, call this preorder number Num(v) Low(v) is the minimum of 1. Num(v) 2. the lowest Num(w) among all back edges (v, w) 3. the lowest Low(w) among all tree edges (v, w) Step 1: Find DFN Step 2: Do Post order Traversal and Find low value
  • 128. The root is an articulation point if and only if it has more than one child Any other vertex v is an articulation point if and only if v has some child w such that Low(w) ≥ Num(v) Step 3: Rules to find Articulation Point D has a child E, and Low(E) ≥ Num(D) C and D are articulation points C has a child G and Low(G) ≥ Num(C).
  • 129. Example Step 1: Find DFN Step 2: Do Post order Traversal and Find low value Ver tex 0 1 2 3 4 5 6 7 8 9 dfn 4 3 2 0 1 5 6 7 9 8 low 4 0 0 0 0 5 5 5 9 8
  • 130. the root, vertex 3, is an articulation point because it has more than one child. vertex 1 is an articulation point since it has a child 0 such that low (0) ≥ dfn (1) Vertex 7 is also an articulation point since low (8) ≥ dfn (7) vertex 5 is also an articulation point since low (6) ≥ dfn (5). Ver tex 0 1 2 3 4 5 6 7 8 9 dfn 4 3 2 0 1 5 6 7 9 8 low 4 0 0 0 0 5 5 5 9 8
  • 131. Euler circuit Eulerian path and circuit for undirected graph • Eulerian Path is a path in graph that visits every edge exactly once. • Eulerian Circuit is an Eulerian Path which starts and ends on the same vertex. • An Euler path starts and ends at different vertices. • An Euler circuit starts and ends at the same vertex • A graph is called Eulerian if it has an Eulerian Cycle and called Semi-Eulerian if it has an Eulerian Path
  • 132. Euler Path Eg Euler Path to exist in a graph, exactly 0 or 2 vertices must have odd degree Start with one of the odd vertices. End in the other one
  • 133. Euler Circuit All vertices must have even degree
  • 134. Condition for Euler Path and Euler Circuit
  • 135. DFS to find Euler circuit 2 , 1, 0, 2 2, 1,0, 3,4,0,2  Start with any vertex s.  First, using DFS find any circuit starting and ending in s.  Mark all edges on the circuit as visited  While there are still edges in the graph that are not marked visited: • Find the first vertex v on the circuit that has unvisited edges. • Find a circuit starting in v and splice this path into the first circuit 1,0,2,1 1,0,3,4,0,2,1 Solution 1 Solution 2