SlideShare a Scribd company logo
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

PDF
Wasserstein GAN 수학 이해하기 I
Sungbin Lim
 
PDF
Facebook Open Graph API and How To Use It
Aayush Shrestha
 
PPTX
Machine Learning Tutorial Part - 1 | Machine Learning Tutorial For Beginners ...
Simplilearn
 
PDF
Abstractive Text Summarization
Tho Phan
 
PPT
Pattern matching
shravs_188
 
PPTX
Machine Learning Tutorial Part - 2 | Machine Learning Tutorial For Beginners ...
Simplilearn
 
PDF
Multi-armed Bandits
Dongmin Lee
 
PPTX
Support vector machine
Musa Hawamdah
 
Wasserstein GAN 수학 이해하기 I
Sungbin Lim
 
Facebook Open Graph API and How To Use It
Aayush Shrestha
 
Machine Learning Tutorial Part - 1 | Machine Learning Tutorial For Beginners ...
Simplilearn
 
Abstractive Text Summarization
Tho Phan
 
Pattern matching
shravs_188
 
Machine Learning Tutorial Part - 2 | Machine Learning Tutorial For Beginners ...
Simplilearn
 
Multi-armed Bandits
Dongmin Lee
 
Support vector machine
Musa Hawamdah
 

What's hot (20)

PPTX
Chapter 09 design and analysis of algorithms
Praveen M Jigajinni
 
PDF
Neural Machine Translation (D3L4 Deep Learning for Speech and Language UPC 2017)
Universitat Politècnica de Catalunya
 
PPTX
Neural networks
Slideshare
 
PDF
AI 5 | Local Search
Mohammad Imam Hossain
 
PDF
Shortest path algorithms
Amit Kumar Rathi
 
PPT
Planning
ahmad bassiouny
 
PPT
Multi-Layer Perceptrons
ESCOM
 
PDF
Machine Learning Course | Edureka
Edureka!
 
PPTX
A* Algorithm
Dr. C.V. Suresh Babu
 
PPTX
An introduction to reinforcement learning
Subrat Panda, PhD
 
PPTX
And or graph problem reduction using predicate logic
Mohanlal Sukhadia University (MLSU)
 
PPT
AI Lecture 5 (game playing)
Tajim Md. Niamat Ullah Akhund
 
PPT
2.17Mb ppt
butest
 
PDF
Scikit Learn Tutorial | Machine Learning with Python | Python for Data Scienc...
Edureka!
 
PPTX
8 queens problem using back tracking
Tech_MX
 
PDF
What is Machine Learning | Introduction to Machine Learning | Machine Learnin...
Simplilearn
 
PPTX
Inference in First-Order Logic
Junya Tanaka
 
PDF
Natural Language Processing (NLP) & Text Mining Tutorial Using NLTK | NLP Tra...
Edureka!
 
PPTX
Apriori algorithm
Mainul Hassan
 
PPTX
Post Machine
Saira Fazal Qader
 
Chapter 09 design and analysis of algorithms
Praveen M Jigajinni
 
Neural Machine Translation (D3L4 Deep Learning for Speech and Language UPC 2017)
Universitat Politècnica de Catalunya
 
Neural networks
Slideshare
 
AI 5 | Local Search
Mohammad Imam Hossain
 
Shortest path algorithms
Amit Kumar Rathi
 
Planning
ahmad bassiouny
 
Multi-Layer Perceptrons
ESCOM
 
Machine Learning Course | Edureka
Edureka!
 
A* Algorithm
Dr. C.V. Suresh Babu
 
An introduction to reinforcement learning
Subrat Panda, PhD
 
And or graph problem reduction using predicate logic
Mohanlal Sukhadia University (MLSU)
 
AI Lecture 5 (game playing)
Tajim Md. Niamat Ullah Akhund
 
2.17Mb ppt
butest
 
Scikit Learn Tutorial | Machine Learning with Python | Python for Data Scienc...
Edureka!
 
8 queens problem using back tracking
Tech_MX
 
What is Machine Learning | Introduction to Machine Learning | Machine Learnin...
Simplilearn
 
Inference in First-Order Logic
Junya Tanaka
 
Natural Language Processing (NLP) & Text Mining Tutorial Using NLTK | NLP Tra...
Edureka!
 
Apriori algorithm
Mainul Hassan
 
Post Machine
Saira Fazal Qader
 
Ad

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

PPSX
Design and analysis of Algorithms Lecture 1 (BFS, DFS).ppsx
SababAshfakFahim
 
PPT
Breadth first search
Sazzad Hossain
 
PPT
Chapter 23 aoa
Hanif Durad
 
PPT
Graphs Presentation of University by Coordinator
haseebanjum2611
 
PPT
lec 09-graphs-bfs-dfs.ppt
TalhaFarooqui12
 
PDF
Talk on Graph Theory - I
Anirudh Raja
 
PPTX
Data Structures and Agorithm: DS 21 Graph Theory.pptx
RashidFaridChishti
 
PDF
Analysis and design of algorithms part 3
Deepak John
 
PPTX
Lecture 5 - Graph Algorithms BFS and DFS.pptx
mtahanasir65
 
PPTX
logic.pptx
KENNEDY GITHAIGA
 
PDF
Bfs dfs
Amit Kumar Rathi
 
PPTX
DATA STRUCTURES.pptx
KENNEDY GITHAIGA
 
PDF
Graph Data Structure
Keno benti
 
PPTX
Algorithm Design and Complexity - Course 7
Traian Rebedea
 
PPTX
Graph Representation, DFS and BFS Presentation.pptx
bashirabdullah789
 
PDF
Graphs
Dwight Sabio
 
PDF
Daa chpater 12
B.Kirron Reddi
 
PPT
Lecture 5b graphs and hashing
Victor Palmar
 
PPTX
Graph Data Structure
Afaq Mansoor Khan
 
PDF
Unit-10 Graphs .pdf
Yatru Harsha Hiski
 
Design and analysis of Algorithms Lecture 1 (BFS, DFS).ppsx
SababAshfakFahim
 
Breadth first search
Sazzad Hossain
 
Chapter 23 aoa
Hanif Durad
 
Graphs Presentation of University by Coordinator
haseebanjum2611
 
lec 09-graphs-bfs-dfs.ppt
TalhaFarooqui12
 
Talk on Graph Theory - I
Anirudh Raja
 
Data Structures and Agorithm: DS 21 Graph Theory.pptx
RashidFaridChishti
 
Analysis and design of algorithms part 3
Deepak John
 
Lecture 5 - Graph Algorithms BFS and DFS.pptx
mtahanasir65
 
logic.pptx
KENNEDY GITHAIGA
 
DATA STRUCTURES.pptx
KENNEDY GITHAIGA
 
Graph Data Structure
Keno benti
 
Algorithm Design and Complexity - Course 7
Traian Rebedea
 
Graph Representation, DFS and BFS Presentation.pptx
bashirabdullah789
 
Graphs
Dwight Sabio
 
Daa chpater 12
B.Kirron Reddi
 
Lecture 5b graphs and hashing
Victor Palmar
 
Graph Data Structure
Afaq Mansoor Khan
 
Unit-10 Graphs .pdf
Yatru Harsha Hiski
 
Ad

More from Md. Shafiuzzaman Hira (20)

PPTX
Introduction to Web development
Md. Shafiuzzaman Hira
 
PPTX
Software measurement and estimation
Md. Shafiuzzaman Hira
 
PPTX
Why do we test software?
Md. Shafiuzzaman Hira
 
PPT
Software Requirements engineering
Md. Shafiuzzaman Hira
 
PPTX
Software architectural patterns
Md. Shafiuzzaman Hira
 
PPTX
Class based modeling
Md. Shafiuzzaman Hira
 
PPTX
Class diagram
Md. Shafiuzzaman Hira
 
PPTX
State diagram
Md. Shafiuzzaman Hira
 
PDF
Use case Modeling
Md. Shafiuzzaman Hira
 
PDF
User stories
Md. Shafiuzzaman Hira
 
PDF
Agile Methodology
Md. Shafiuzzaman Hira
 
PDF
Software Process Model
Md. Shafiuzzaman Hira
 
PDF
Introduction to Software Engineering Course
Md. Shafiuzzaman Hira
 
PPTX
C pointers
Md. Shafiuzzaman Hira
 
PPTX
C structures
Md. Shafiuzzaman Hira
 
PPTX
How to Create Python scripts
Md. Shafiuzzaman Hira
 
PPTX
Regular expressions using Python
Md. Shafiuzzaman Hira
 
PPTX
Password locker project
Md. Shafiuzzaman Hira
 
Introduction to Web development
Md. Shafiuzzaman Hira
 
Software measurement and estimation
Md. Shafiuzzaman Hira
 
Why do we test software?
Md. Shafiuzzaman Hira
 
Software Requirements engineering
Md. Shafiuzzaman Hira
 
Software architectural patterns
Md. Shafiuzzaman Hira
 
Class based modeling
Md. Shafiuzzaman Hira
 
Class diagram
Md. Shafiuzzaman Hira
 
State diagram
Md. Shafiuzzaman Hira
 
Use case Modeling
Md. Shafiuzzaman Hira
 
User stories
Md. Shafiuzzaman Hira
 
Agile Methodology
Md. Shafiuzzaman Hira
 
Software Process Model
Md. Shafiuzzaman Hira
 
Introduction to Software Engineering Course
Md. Shafiuzzaman Hira
 
C structures
Md. Shafiuzzaman Hira
 
How to Create Python scripts
Md. Shafiuzzaman Hira
 
Regular expressions using Python
Md. Shafiuzzaman Hira
 
Password locker project
Md. Shafiuzzaman Hira
 

Recently uploaded (20)

PDF
Software Testing Tools - names and explanation
shruti533256
 
PDF
Traditional Exams vs Continuous Assessment in Boarding Schools.pdf
The Asian School
 
PDF
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
PDF
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
PPTX
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PPT
SCOPE_~1- technology of green house and poyhouse
bala464780
 
PPTX
Information Retrieval and Extraction - Module 7
premSankar19
 
PDF
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
PDF
Principles of Food Science and Nutritions
Dr. Yogesh Kumar Kosariya
 
PDF
Zero carbon Building Design Guidelines V4
BassemOsman1
 
PDF
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
PPTX
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
PPTX
AgentX UiPath Community Webinar series - Delhi
RohitRadhakrishnan8
 
PPTX
easa module 3 funtamental electronics.pptx
tryanothert7
 
PDF
July 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
PDF
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
PPTX
Color Model in Textile ( RGB, CMYK).pptx
auladhossain191
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PDF
Introduction to Data Science: data science process
ShivarkarSandip
 
Software Testing Tools - names and explanation
shruti533256
 
Traditional Exams vs Continuous Assessment in Boarding Schools.pdf
The Asian School
 
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
SCOPE_~1- technology of green house and poyhouse
bala464780
 
Information Retrieval and Extraction - Module 7
premSankar19
 
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
Principles of Food Science and Nutritions
Dr. Yogesh Kumar Kosariya
 
Zero carbon Building Design Guidelines V4
BassemOsman1
 
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
AgentX UiPath Community Webinar series - Delhi
RohitRadhakrishnan8
 
easa module 3 funtamental electronics.pptx
tryanothert7
 
July 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
Color Model in Textile ( RGB, CMYK).pptx
auladhossain191
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Introduction to Data Science: data science process
ShivarkarSandip
 

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