SlideShare a Scribd company logo
1 of 28
Graph Algorithms: BFS
Prepared by
Md. Shafiuzzaman
Lecturer, Dept. of CSE, JUST
2
Graphs
v1
v2
v5
v7
v8
v3
v6
v4
● A graph G = (V, E)
■ V: set of vertices (nodes)
■ E: set of edges (links)
● Complete graph
■ There is an edge between every pair of
vertices
● Two kinds of graph
■ Undirected
■ Directed (digraph)
● Undirected graph:
■ E consists of sets of two elements each:
Edge {u, v} is the same as {v, u}
Md. Shafiuzzaman
3
Directed Graphs
v1
v2
v5
v7
v8
v3
v6
v4
● A directed graph, or
digraph:
■ E is set of ordered pairs
■ Even if edge (u, v) is
present, the edge (v, u)
may be absent
● Directed graphs are
drawn with nodes for
vertices and arrows for
edges
Md. Shafiuzzaman
4
Terminology
● Adjacency
■ Vertex w is adjacent to v if and only
(v, w) is in E
● Weight
■ A cost parameter associated with
each edge
● Path
■ A sequence of vertices w1,w2,…,wn,
where there is an edge for each pair
of consecutive vertices
● Length of a path
■ Number of edges along path
■ Length of path of n vertices is n-1
● Cost of a path
■ sum of the weights of the edges
along the path
v1
v2
v5
v7
v8
v3
v6
v4
3
1
-1
5 2
-2
4
Md. Shafiuzzaman
Md. Shafiuzzaman
Representing Graphs
● Assume V = {1, 2, …, n}
● An adjacency matrix represents the graph as a
n x n matrix A:
■ A[i, j] = 1 if edge (i, j)  E (or weight of edge)
= 0 if edge (i, j)  E
Md. Shafiuzzaman
Graphs: Adjacency Matrix
● Example:
1
2 4
3
a
d
b c
A 1 2 3 4
1
2
3
??
4
Md. Shafiuzzaman
Graphs: Adjacency Matrix
● Example:
1
2 4
3
a
d
b c
A 1 2 3 4
1 0 1 1 0
2 0 0 1 0
3 0 0 0 0
4 0 0 1 0
Md. Shafiuzzaman
Graphs: Adjacency List
● Adjacency list: for each vertex v  V, store a
list of vertices adjacent to v
● Example:
■ Adj[1] = {2,3}
■ Adj[2] = {3}
■ Adj[3] = {}
■ Adj[4] = {3}
● Variation: can also keep
a list of edges coming into vertex
1
2 4
3
Md. Shafiuzzaman
Graph Searching
● Given: a graph G = (V, E), directed or
undirected
● Goal: methodically explore every vertex and
every edge
● Ultimately: build a tree on the graph
■ Pick a vertex as the root
■ Choose certain edges to produce a tree
Md. Shafiuzzaman
Breadth-First Search
● “Explore” a graph, turning it into a tree
■ One vertex at a time
■ Expand frontier of explored vertices across the
breadth of the frontier
● Builds a tree over the graph
■ Pick a source vertex to be the root
■ Find (“discover”) its children, then their children,
etc.
Md. Shafiuzzaman
Breadth-First Search
● Again will associate vertex “colors” to guide
the algorithm
■ White vertices have not been discovered
○ All vertices start out white
■ Grey vertices are discovered but not fully explored
○ They may be adjacent to white vertices
■ Black vertices are discovered and fully explored
○ They are adjacent only to black and gray vertices
● Explore vertices by scanning adjacency list of
grey vertices
Md. Shafiuzzaman
Breadth-First Search: Example








r s t u
v w x y
Md. Shafiuzzaman
Breadth-First Search: Example


0





r s t u
v w x y
sQ:
Md. Shafiuzzaman
Breadth-First Search: Example
1

0
1




r s t u
v w x y
wQ: r
Md. Shafiuzzaman
Breadth-First Search: Example
1

0
1
2
2


r s t u
v w x y
rQ: t x
Md. Shafiuzzaman
Breadth-First Search: Example
1
2
0
1
2
2


r s t u
v w x y
Q: t x v
Md. Shafiuzzaman
Breadth-First Search: Example
1
2
0
1
2
2
3

r s t u
v w x y
Q: x v u
Md. Shafiuzzaman
Breadth-First Search: Example
1
2
0
1
2
2
3
3
r s t u
v w x y
Q: v u y
Md. Shafiuzzaman
Breadth-First Search: Example
1
2
0
1
2
2
3
3
r s t u
v w x y
Q: u y
Md. Shafiuzzaman
Breadth-First Search: Example
1
2
0
1
2
2
3
3
r s t u
v w x y
Q: y
Md. Shafiuzzaman
Breadth-First Search: Example
1
2
0
1
2
2
3
3
r s t u
v w x y
Q: Ø
Md. Shafiuzzaman
Breadth-First Search
BFS(G, s) {
initialize vertices;
Q = {s}; // Q is a queue; initialize to s
while (Q not empty) {
u = RemoveTop(Q);
for each v  u->adj {
if (v->color == WHITE)
v->color = GREY;
v->d = u->d + 1;
v->p = u;
Enqueue(Q, v);
}
u->color = BLACK;
}
}
What does v->p represent?
What does v->d represent?
Md. Shafiuzzaman
BFS: The Code Again
BFS(G, s) {
initialize vertices;
Q = {s};
while (Q not empty) {
u = RemoveTop(Q);
for each v  u->adj {
if (v->color == WHITE)
v->color = GREY;
v->d = u->d + 1;
v->p = u;
Enqueue(Q, v);
}
u->color = BLACK;
}
}
What will be the running time?
Touch every vertex: O(V)
u = every vertex, but only once
(Why?)
So v = every vertex
that appears in
some other vert’s
adjacency list
Total running time: O(V+E)
Assignment
Given an adjacency matrix representation of a
graph, compute the shortest path from a source
vertex to a goal vertex using Breadth First
Search. In case of a tie, a smaller indexed vertex
should be preferable to a larger indexed vertex.
Md. Shafiuzzaman
Input
The first line is the number of test cases.
Thereafter, for every test case, the first line of
input is n, the number of vertices in the graph.
Then n lines of inputs have n integers each,
separated by a space, denoting the adjacency
matrix. The next line of input is the index of
source and goal, the indexing starts from 0.
Md. Shafiuzzaman
Sample Input
1
5
0 1 1 0 0
1 0 1 0 0
1 1 0 1 0
0 0 1 0 1
0 0 0 1 0
0 4
Md. Shafiuzzaman
Output
The first line of output is the cost of shortest path
from source to goal. The second line of output is
the path from source to goal (including both
source and goal).
Md. Shafiuzzaman
Sample Output
3
0 2 3 4
Md. Shafiuzzaman

More Related Content

What's hot

Breadth first search and depth first search
Breadth first search and  depth first searchBreadth first search and  depth first search
Breadth first search and depth first searchHossain Md Shakhawat
 
Bfs & dfs application
Bfs & dfs applicationBfs & dfs application
Bfs & dfs applicationUmme habiba
 
Depth First Search and Breadth First Search
Depth First Search and Breadth First SearchDepth First Search and Breadth First Search
Depth First Search and Breadth First SearchBenjamin Sach
 
BFS, Breadth first search | Search Traversal Algorithm
BFS, Breadth first search | Search Traversal AlgorithmBFS, Breadth first search | Search Traversal Algorithm
BFS, Breadth first search | Search Traversal AlgorithmMSA Technosoft
 
Depth first search [dfs]
Depth first search [dfs]Depth first search [dfs]
Depth first search [dfs]DEEPIKA T
 
Data structures and algorithms lab7
Data structures and algorithms lab7Data structures and algorithms lab7
Data structures and algorithms lab7Bianca Teşilă
 
Depth First Search ( DFS )
Depth First Search ( DFS )Depth First Search ( DFS )
Depth First Search ( DFS )Sazzad Hossain
 
Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Shuvongkor Barman
 
Depth firstsearchalgorithm
Depth firstsearchalgorithmDepth firstsearchalgorithm
Depth firstsearchalgorithmhansa khan
 
Problem Solving with Algorithms and Data Structure - Graphs
Problem Solving with Algorithms and Data Structure - GraphsProblem Solving with Algorithms and Data Structure - Graphs
Problem Solving with Algorithms and Data Structure - GraphsYi-Lung Tsai
 
Graph traversal-BFS & DFS
Graph traversal-BFS & DFSGraph traversal-BFS & DFS
Graph traversal-BFS & DFSRajandeep Gill
 

What's hot (20)

Breadth first search and depth first search
Breadth first search and  depth first searchBreadth first search and  depth first search
Breadth first search and depth first search
 
Bfs dfs
Bfs dfsBfs dfs
Bfs dfs
 
Bfs & dfs application
Bfs & dfs applicationBfs & dfs application
Bfs & dfs application
 
130210107039 2130702
130210107039 2130702130210107039 2130702
130210107039 2130702
 
Depth First Search and Breadth First Search
Depth First Search and Breadth First SearchDepth First Search and Breadth First Search
Depth First Search and Breadth First Search
 
BFS, Breadth first search | Search Traversal Algorithm
BFS, Breadth first search | Search Traversal AlgorithmBFS, Breadth first search | Search Traversal Algorithm
BFS, Breadth first search | Search Traversal Algorithm
 
Depth first search [dfs]
Depth first search [dfs]Depth first search [dfs]
Depth first search [dfs]
 
Data structures and algorithms lab7
Data structures and algorithms lab7Data structures and algorithms lab7
Data structures and algorithms lab7
 
Depth First Search ( DFS )
Depth First Search ( DFS )Depth First Search ( DFS )
Depth First Search ( DFS )
 
Graph
GraphGraph
Graph
 
Bfs dfs
Bfs dfsBfs dfs
Bfs dfs
 
Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)Presentation on Breadth First Search (BFS)
Presentation on Breadth First Search (BFS)
 
Data Structures - Lecture 10 [Graphs]
Data Structures - Lecture 10 [Graphs]Data Structures - Lecture 10 [Graphs]
Data Structures - Lecture 10 [Graphs]
 
Depth firstsearchalgorithm
Depth firstsearchalgorithmDepth firstsearchalgorithm
Depth firstsearchalgorithm
 
Problem Solving with Algorithms and Data Structure - Graphs
Problem Solving with Algorithms and Data Structure - GraphsProblem Solving with Algorithms and Data Structure - Graphs
Problem Solving with Algorithms and Data Structure - Graphs
 
Bfs and Dfs
Bfs and DfsBfs and Dfs
Bfs and Dfs
 
Topological Sort
Topological SortTopological Sort
Topological Sort
 
Graph traversal-BFS & DFS
Graph traversal-BFS & DFSGraph traversal-BFS & DFS
Graph traversal-BFS & DFS
 
Bfs
BfsBfs
Bfs
 
Depth-First Search
Depth-First SearchDepth-First Search
Depth-First Search
 

Similar to Graph Algorithms: Breadth-First Search (BFS)

Similar to Graph Algorithms: Breadth-First Search (BFS) (20)

Unit ix graph
Unit   ix    graph Unit   ix    graph
Unit ix graph
 
Unit 9 graph
Unit   9 graphUnit   9 graph
Unit 9 graph
 
Graph Representation, DFS and BFS Presentation.pptx
Graph Representation, DFS and BFS Presentation.pptxGraph Representation, DFS and BFS Presentation.pptx
Graph Representation, DFS and BFS Presentation.pptx
 
lec 09-graphs-bfs-dfs.ppt
lec 09-graphs-bfs-dfs.pptlec 09-graphs-bfs-dfs.ppt
lec 09-graphs-bfs-dfs.ppt
 
B.tech admission in india
B.tech admission in indiaB.tech admission in india
B.tech admission in india
 
Chapter 23 aoa
Chapter 23 aoaChapter 23 aoa
Chapter 23 aoa
 
8.-Graphs information technologies graph
8.-Graphs information technologies graph8.-Graphs information technologies graph
8.-Graphs information technologies graph
 
Unit 2: All
Unit 2: AllUnit 2: All
Unit 2: All
 
Graphs
GraphsGraphs
Graphs
 
Graph ASS DBATU.pptx
Graph ASS DBATU.pptxGraph ASS DBATU.pptx
Graph ASS DBATU.pptx
 
Graph
GraphGraph
Graph
 
Graph in data structure
Graph in data structureGraph in data structure
Graph in data structure
 
Graph ds
Graph dsGraph ds
Graph ds
 
graph ASS (1).ppt
graph ASS (1).pptgraph ASS (1).ppt
graph ASS (1).ppt
 
Graps 2
Graps 2Graps 2
Graps 2
 
6. Graphs
6. Graphs6. Graphs
6. Graphs
 
Unit-6 Graph.ppsx ppt
Unit-6 Graph.ppsx                                       pptUnit-6 Graph.ppsx                                       ppt
Unit-6 Graph.ppsx ppt
 
graph.pptx
graph.pptxgraph.pptx
graph.pptx
 
LEC 12-DSALGO-GRAPHS(final12).pdf
LEC 12-DSALGO-GRAPHS(final12).pdfLEC 12-DSALGO-GRAPHS(final12).pdf
LEC 12-DSALGO-GRAPHS(final12).pdf
 
14 chapter9 graph_algorithmstopologicalsort_shortestpath
14 chapter9 graph_algorithmstopologicalsort_shortestpath14 chapter9 graph_algorithmstopologicalsort_shortestpath
14 chapter9 graph_algorithmstopologicalsort_shortestpath
 

More from Md. Shafiuzzaman Hira (20)

Introduction to Web development
Introduction to Web developmentIntroduction to Web development
Introduction to Web development
 
Software measurement and estimation
Software measurement and estimationSoftware measurement and estimation
Software measurement and estimation
 
Why do we test software?
Why do we test software?Why do we test software?
Why do we test software?
 
Software Requirements engineering
Software Requirements engineeringSoftware Requirements engineering
Software Requirements engineering
 
Software architectural patterns
Software architectural patternsSoftware architectural patterns
Software architectural patterns
 
Class based modeling
Class based modelingClass based modeling
Class based modeling
 
Class diagram
Class diagramClass diagram
Class diagram
 
State diagram
State diagramState diagram
State diagram
 
Use case Modeling
Use case ModelingUse case Modeling
Use case Modeling
 
User stories
User storiesUser stories
User stories
 
Dev ops
Dev opsDev ops
Dev ops
 
Agile Methodology
Agile MethodologyAgile Methodology
Agile Methodology
 
Software Process Model
Software Process ModelSoftware Process Model
Software Process Model
 
Introduction to Software Engineering Course
Introduction to Software Engineering CourseIntroduction to Software Engineering Course
Introduction to Software Engineering Course
 
C files
C filesC files
C files
 
C pointers
C pointersC pointers
C pointers
 
C structures
C structuresC structures
C structures
 
How to Create Python scripts
How to Create Python scriptsHow to Create Python scripts
How to Create Python scripts
 
Regular expressions using Python
Regular expressions using PythonRegular expressions using Python
Regular expressions using Python
 
Password locker project
Password locker project Password locker project
Password locker project
 

Recently uploaded

HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage examplePragyanshuParadkar1
 

Recently uploaded (20)

POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage example
 

Graph Algorithms: Breadth-First Search (BFS)

  • 1. Graph Algorithms: BFS Prepared by Md. Shafiuzzaman Lecturer, Dept. of CSE, JUST
  • 2. 2 Graphs v1 v2 v5 v7 v8 v3 v6 v4 ● A graph G = (V, E) ■ V: set of vertices (nodes) ■ E: set of edges (links) ● Complete graph ■ There is an edge between every pair of vertices ● Two kinds of graph ■ Undirected ■ Directed (digraph) ● Undirected graph: ■ E consists of sets of two elements each: Edge {u, v} is the same as {v, u} Md. Shafiuzzaman
  • 3. 3 Directed Graphs v1 v2 v5 v7 v8 v3 v6 v4 ● A directed graph, or digraph: ■ E is set of ordered pairs ■ Even if edge (u, v) is present, the edge (v, u) may be absent ● Directed graphs are drawn with nodes for vertices and arrows for edges Md. Shafiuzzaman
  • 4. 4 Terminology ● Adjacency ■ Vertex w is adjacent to v if and only (v, w) is in E ● Weight ■ A cost parameter associated with each edge ● Path ■ A sequence of vertices w1,w2,…,wn, where there is an edge for each pair of consecutive vertices ● Length of a path ■ Number of edges along path ■ Length of path of n vertices is n-1 ● Cost of a path ■ sum of the weights of the edges along the path v1 v2 v5 v7 v8 v3 v6 v4 3 1 -1 5 2 -2 4 Md. Shafiuzzaman
  • 5. Md. Shafiuzzaman Representing Graphs ● Assume V = {1, 2, …, n} ● An adjacency matrix represents the graph as a n x n matrix A: ■ A[i, j] = 1 if edge (i, j)  E (or weight of edge) = 0 if edge (i, j)  E
  • 6. Md. Shafiuzzaman Graphs: Adjacency Matrix ● Example: 1 2 4 3 a d b c A 1 2 3 4 1 2 3 ?? 4
  • 7. Md. Shafiuzzaman Graphs: Adjacency Matrix ● Example: 1 2 4 3 a d b c A 1 2 3 4 1 0 1 1 0 2 0 0 1 0 3 0 0 0 0 4 0 0 1 0
  • 8. Md. Shafiuzzaman Graphs: Adjacency List ● Adjacency list: for each vertex v  V, store a list of vertices adjacent to v ● Example: ■ Adj[1] = {2,3} ■ Adj[2] = {3} ■ Adj[3] = {} ■ Adj[4] = {3} ● Variation: can also keep a list of edges coming into vertex 1 2 4 3
  • 9. Md. Shafiuzzaman Graph Searching ● Given: a graph G = (V, E), directed or undirected ● Goal: methodically explore every vertex and every edge ● Ultimately: build a tree on the graph ■ Pick a vertex as the root ■ Choose certain edges to produce a tree
  • 10. Md. Shafiuzzaman Breadth-First Search ● “Explore” a graph, turning it into a tree ■ One vertex at a time ■ Expand frontier of explored vertices across the breadth of the frontier ● Builds a tree over the graph ■ Pick a source vertex to be the root ■ Find (“discover”) its children, then their children, etc.
  • 11. Md. Shafiuzzaman Breadth-First Search ● Again will associate vertex “colors” to guide the algorithm ■ White vertices have not been discovered ○ All vertices start out white ■ Grey vertices are discovered but not fully explored ○ They may be adjacent to white vertices ■ Black vertices are discovered and fully explored ○ They are adjacent only to black and gray vertices ● Explore vertices by scanning adjacency list of grey vertices
  • 12. Md. Shafiuzzaman Breadth-First Search: Example         r s t u v w x y
  • 13. Md. Shafiuzzaman Breadth-First Search: Example   0      r s t u v w x y sQ:
  • 14. Md. Shafiuzzaman Breadth-First Search: Example 1  0 1     r s t u v w x y wQ: r
  • 15. Md. Shafiuzzaman Breadth-First Search: Example 1  0 1 2 2   r s t u v w x y rQ: t x
  • 16. Md. Shafiuzzaman Breadth-First Search: Example 1 2 0 1 2 2   r s t u v w x y Q: t x v
  • 17. Md. Shafiuzzaman Breadth-First Search: Example 1 2 0 1 2 2 3  r s t u v w x y Q: x v u
  • 18. Md. Shafiuzzaman Breadth-First Search: Example 1 2 0 1 2 2 3 3 r s t u v w x y Q: v u y
  • 19. Md. Shafiuzzaman Breadth-First Search: Example 1 2 0 1 2 2 3 3 r s t u v w x y Q: u y
  • 20. Md. Shafiuzzaman Breadth-First Search: Example 1 2 0 1 2 2 3 3 r s t u v w x y Q: y
  • 21. Md. Shafiuzzaman Breadth-First Search: Example 1 2 0 1 2 2 3 3 r s t u v w x y Q: Ø
  • 22. Md. Shafiuzzaman Breadth-First Search BFS(G, s) { initialize vertices; Q = {s}; // Q is a queue; initialize to s while (Q not empty) { u = RemoveTop(Q); for each v  u->adj { if (v->color == WHITE) v->color = GREY; v->d = u->d + 1; v->p = u; Enqueue(Q, v); } u->color = BLACK; } } What does v->p represent? What does v->d represent?
  • 23. Md. Shafiuzzaman BFS: The Code Again BFS(G, s) { initialize vertices; Q = {s}; while (Q not empty) { u = RemoveTop(Q); for each v  u->adj { if (v->color == WHITE) v->color = GREY; v->d = u->d + 1; v->p = u; Enqueue(Q, v); } u->color = BLACK; } } What will be the running time? Touch every vertex: O(V) u = every vertex, but only once (Why?) So v = every vertex that appears in some other vert’s adjacency list Total running time: O(V+E)
  • 24. Assignment Given an adjacency matrix representation of a graph, compute the shortest path from a source vertex to a goal vertex using Breadth First Search. In case of a tie, a smaller indexed vertex should be preferable to a larger indexed vertex. Md. Shafiuzzaman
  • 25. Input The first line is the number of test cases. Thereafter, for every test case, the first line of input is n, the number of vertices in the graph. Then n lines of inputs have n integers each, separated by a space, denoting the adjacency matrix. The next line of input is the index of source and goal, the indexing starts from 0. Md. Shafiuzzaman
  • 26. Sample Input 1 5 0 1 1 0 0 1 0 1 0 0 1 1 0 1 0 0 0 1 0 1 0 0 0 1 0 0 4 Md. Shafiuzzaman
  • 27. Output The first line of output is the cost of shortest path from source to goal. The second line of output is the path from source to goal (including both source and goal). Md. Shafiuzzaman
  • 28. Sample Output 3 0 2 3 4 Md. Shafiuzzaman