SlideShare a Scribd company logo
1 of 18
BY…
M.ARCHANA
I-Msc(cs)
Topological sorting:
Topological sorting for Directed Acyclic Graph
(DAG) is a linear ordering of vertices such that for
every directed edge u v, vertex u comes before v in
the ordering.
 Topological Sorting for a graph is not possible if the
graph is not a DAG.
For example, a topological sorting of the following
graph is “5 4 2 3 1 0”. There can be more than one
topological sorting for a graph.
 For example, another topological sorting of the
following graph is “4 5 2 3 1 0”. The rst vertex in
topological sorting is always a vertex with indegree as 0
(a vertex with no incoming edges).
5 4
0
2 1
3
Algorithm to find topological
sorting:
We recommend to first see the implementation of DFS.
We can modify DFS to find Topological Sorting of a
graph.
 In DFS, we start from a vertex, we first print it and then
recursively call DFS for its adjacent vertices.
 In topological sorting, we use a temporary stack. We
don’t print the vertex immediately, we first recursively
call topological sorting for all its adjacent vertices, then
push it to a stack.
 Finally, print contents of the stack. Note that a vertex is
pushed to stack only when all of its adjacent vertices (and
their adjacent vertices and so on) are already in the stack.
Breadth first traversal:
 Breadth First Search (BFS) algorithm traverses a
graph in a breadthward motion and uses a queue to
remember to get the next vertex to start a search,
when a dead end occurs in any iteration.
 Breadth First Traversal (or Search) for a graph is similar to
Breadth First Traversal of a tree (See method 2 of this
post).
 The only catch here is, unlike trees, graphs may contain
cycles, so we may come to the same node again.
Cont.,
 To avoid processing a node more than once, we use a
Boolean visited array.
 For simplicity, it is assumed that all vertices are reachable
from the starting vertex.
 For example, in the following graph, we start traversal
from vertex 2.
 When we come to vertex 0, we look for all adjacent
vertices of it.
 2 is also an adjacent vertex of 0.
 If we don’t mark visited vertices, then 2 will be
processed again and it will become a non-terminating
process.
A Breadth First Traversal of the following graph is 2, 0,
3, 1.
start
0 1
2 3
Example:
cont.,
 As in the example given above, BFS algorithm traverses from
A to B to E to F first then to C and G lastly to D. It employs the
following rules. lastly to D. It employs the following rules.
 Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited.
Display it. Insert it in a − Visit the adjacent unvisited vertex.
Mark it as visited. Display it. Insert it in a queue. queue. Rule
 Rule 2 − If no adjacent vertex is found, remove the first vertex
from the queue. − If no adjacent vertex is found, remove the
first vertex from the queue.
 Rule 3 − Repeat Rule 1 and Rule 2 until the queue is empty.
Step 1:
Initialize the
queue.
Step 2:
We start from
visiting S (starting
node), and mark it
as visited.
Step 3:
We then see an
unvisited adjacent
node from S.
 In this example, we
have three nodes but
alphabetically we
choose nodes A ,
mark it as visited and
enqueue it.
Step 4:
Next, the unvisited
adjacent node from
S is B. We mark it as
visited and enqueue
it.
Step 5:
Next, the unvisited
adjacent node from S
is C. We mark it as
visited and enqueue it
Step 6:
 Now, S is left
with no unvisited
adjacent nodes.
So, we dequeue
and find A.
Step 7:
From A we have
D as unvisited
adjacent node. We
mark it as visited
and enqueue it
Topological Sort and BFS
Topological Sort and BFS

More Related Content

Similar to Topological Sort and BFS

Similar to Topological Sort and BFS (20)

logic.pptx
logic.pptxlogic.pptx
logic.pptx
 
Daa chpater 12
Daa chpater 12Daa chpater 12
Daa chpater 12
 
DATA STRUCTURES.pptx
DATA STRUCTURES.pptxDATA STRUCTURES.pptx
DATA STRUCTURES.pptx
 
Depth first traversal(data structure algorithms)
Depth first traversal(data structure algorithms)Depth first traversal(data structure algorithms)
Depth first traversal(data structure algorithms)
 
Unit V - ppt.pptx
Unit V - ppt.pptxUnit V - ppt.pptx
Unit V - ppt.pptx
 
Graph Theory
Graph TheoryGraph Theory
Graph Theory
 
Graphs
GraphsGraphs
Graphs
 
Unit-6 Graph.ppsx ppt
Unit-6 Graph.ppsx                                       pptUnit-6 Graph.ppsx                                       ppt
Unit-6 Graph.ppsx ppt
 
UNIT III.pptx
UNIT III.pptxUNIT III.pptx
UNIT III.pptx
 
DFS.pptx
DFS.pptxDFS.pptx
DFS.pptx
 
GRAPH - DISCRETE STRUCTURE AND ALGORITHM
GRAPH - DISCRETE STRUCTURE AND ALGORITHMGRAPH - DISCRETE STRUCTURE AND ALGORITHM
GRAPH - DISCRETE STRUCTURE AND ALGORITHM
 
Analysis & design of algorithm
Analysis & design of algorithmAnalysis & design of algorithm
Analysis & design of algorithm
 
Data structure and algorithm
Data structure and algorithmData structure and algorithm
Data structure and algorithm
 
bfs tree searching ,sortingUntitled presentation.pptx
bfs tree searching ,sortingUntitled presentation.pptxbfs tree searching ,sortingUntitled presentation.pptx
bfs tree searching ,sortingUntitled presentation.pptx
 
All Perfect Elimination Orderings & Minimal Vertex Seperators
All Perfect Elimination Orderings & Minimal Vertex SeperatorsAll Perfect Elimination Orderings & Minimal Vertex Seperators
All Perfect Elimination Orderings & Minimal Vertex Seperators
 
ppt 1.pptx
ppt 1.pptxppt 1.pptx
ppt 1.pptx
 
LEC 12-DSALGO-GRAPHS(final12).pdf
LEC 12-DSALGO-GRAPHS(final12).pdfLEC 12-DSALGO-GRAPHS(final12).pdf
LEC 12-DSALGO-GRAPHS(final12).pdf
 
linked list using c
linked list using clinked list using c
linked list using c
 
Data structure computer graphs
Data structure computer graphsData structure computer graphs
Data structure computer graphs
 
Graph in data structure
Graph in data structureGraph in data structure
Graph in data structure
 

More from ArchanaMani2

Software evolution and Verification,validation
Software evolution and Verification,validationSoftware evolution and Verification,validation
Software evolution and Verification,validationArchanaMani2
 
Code scheduling constraints
Code scheduling constraintsCode scheduling constraints
Code scheduling constraintsArchanaMani2
 
Ajax enabled rich internet applications with xml and json
Ajax enabled rich internet applications with xml and jsonAjax enabled rich internet applications with xml and json
Ajax enabled rich internet applications with xml and jsonArchanaMani2
 
Excellence in visulization
Excellence in visulizationExcellence in visulization
Excellence in visulizationArchanaMani2
 
Transaction management
Transaction managementTransaction management
Transaction managementArchanaMani2
 
Inheritance and overriding
Inheritance  and overridingInheritance  and overriding
Inheritance and overridingArchanaMani2
 

More from ArchanaMani2 (10)

Software evolution and Verification,validation
Software evolution and Verification,validationSoftware evolution and Verification,validation
Software evolution and Verification,validation
 
Code scheduling constraints
Code scheduling constraintsCode scheduling constraints
Code scheduling constraints
 
Ajax enabled rich internet applications with xml and json
Ajax enabled rich internet applications with xml and jsonAjax enabled rich internet applications with xml and json
Ajax enabled rich internet applications with xml and json
 
Excellence in visulization
Excellence in visulizationExcellence in visulization
Excellence in visulization
 
Firewall
FirewallFirewall
Firewall
 
The linux system
The linux systemThe linux system
The linux system
 
Big data
Big dataBig data
Big data
 
Transaction management
Transaction managementTransaction management
Transaction management
 
Genetic algorithm
Genetic algorithmGenetic algorithm
Genetic algorithm
 
Inheritance and overriding
Inheritance  and overridingInheritance  and overriding
Inheritance and overriding
 

Recently uploaded

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 

Recently uploaded (20)

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 

Topological Sort and BFS

  • 2. Topological sorting: Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge u v, vertex u comes before v in the ordering.  Topological Sorting for a graph is not possible if the graph is not a DAG. For example, a topological sorting of the following graph is “5 4 2 3 1 0”. There can be more than one topological sorting for a graph.
  • 3.  For example, another topological sorting of the following graph is “4 5 2 3 1 0”. The rst vertex in topological sorting is always a vertex with indegree as 0 (a vertex with no incoming edges). 5 4 0 2 1 3
  • 4. Algorithm to find topological sorting: We recommend to first see the implementation of DFS. We can modify DFS to find Topological Sorting of a graph.  In DFS, we start from a vertex, we first print it and then recursively call DFS for its adjacent vertices.  In topological sorting, we use a temporary stack. We don’t print the vertex immediately, we first recursively call topological sorting for all its adjacent vertices, then push it to a stack.  Finally, print contents of the stack. Note that a vertex is pushed to stack only when all of its adjacent vertices (and their adjacent vertices and so on) are already in the stack.
  • 5. Breadth first traversal:  Breadth First Search (BFS) algorithm traverses a graph in a breadthward motion and uses a queue to remember to get the next vertex to start a search, when a dead end occurs in any iteration.  Breadth First Traversal (or Search) for a graph is similar to Breadth First Traversal of a tree (See method 2 of this post).  The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again.
  • 6. Cont.,  To avoid processing a node more than once, we use a Boolean visited array.  For simplicity, it is assumed that all vertices are reachable from the starting vertex.  For example, in the following graph, we start traversal from vertex 2.  When we come to vertex 0, we look for all adjacent vertices of it.  2 is also an adjacent vertex of 0.  If we don’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process.
  • 7. A Breadth First Traversal of the following graph is 2, 0, 3, 1. start 0 1 2 3
  • 9. cont.,  As in the example given above, BFS algorithm traverses from A to B to E to F first then to C and G lastly to D. It employs the following rules. lastly to D. It employs the following rules.  Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it in a − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it in a queue. queue. Rule  Rule 2 − If no adjacent vertex is found, remove the first vertex from the queue. − If no adjacent vertex is found, remove the first vertex from the queue.  Rule 3 − Repeat Rule 1 and Rule 2 until the queue is empty.
  • 11. Step 2: We start from visiting S (starting node), and mark it as visited.
  • 12. Step 3: We then see an unvisited adjacent node from S.  In this example, we have three nodes but alphabetically we choose nodes A , mark it as visited and enqueue it.
  • 13. Step 4: Next, the unvisited adjacent node from S is B. We mark it as visited and enqueue it.
  • 14. Step 5: Next, the unvisited adjacent node from S is C. We mark it as visited and enqueue it
  • 15. Step 6:  Now, S is left with no unvisited adjacent nodes. So, we dequeue and find A.
  • 16. Step 7: From A we have D as unvisited adjacent node. We mark it as visited and enqueue it