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

What's hot

Introduction on Prolog - Programming in Logic
Introduction on Prolog - Programming in LogicIntroduction on Prolog - Programming in Logic
Introduction on Prolog - Programming in Logic
Vishal Tandel
 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notations
Ehtisham Ali
 
Prims and kruskal algorithms
Prims and kruskal algorithmsPrims and kruskal algorithms
Prims and kruskal algorithms
Saga Valsalan
 
Graphs bfs dfs
Graphs bfs dfsGraphs bfs dfs
Graphs bfs dfs
Jaya Gautam
 
Rabin Carp String Matching algorithm
Rabin Carp String Matching  algorithmRabin Carp String Matching  algorithm
Rabin Carp String Matching algorithm
sabiya sabiya
 
Prim's Algorithm on minimum spanning tree
Prim's Algorithm on minimum spanning treePrim's Algorithm on minimum spanning tree
Prim's Algorithm on minimum spanning tree
oneous
 
Depth First Search ( DFS )
Depth First Search ( DFS )Depth First Search ( DFS )
Depth First Search ( DFS )
Sazzad Hossain
 
Hierarchical clustering
Hierarchical clusteringHierarchical clustering
Hierarchical clustering
ishmecse13
 
Asymptotic notation
Asymptotic notationAsymptotic notation
Asymptotic notation
mustafa sarac
 
Kruskal's algorithm
Kruskal's algorithmKruskal's algorithm
Kruskal's algorithm
Raj Kumar Ranabhat
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
Melaku Bayih Demessie
 
Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
Protap Mondal
 
Spanning trees
Spanning treesSpanning trees
Spanning trees
Shareb Ismaeel
 
Analysis of algorithm
Analysis of algorithmAnalysis of algorithm
Analysis of algorithm
Rajendra Dangwal
 
SINGLE-SOURCE SHORTEST PATHS
SINGLE-SOURCE SHORTEST PATHS SINGLE-SOURCE SHORTEST PATHS
SINGLE-SOURCE SHORTEST PATHS
Md. Shafiuzzaman Hira
 
Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures
Gurukul Kangri Vishwavidyalaya - Faculty of Engineering and Technology
 
Binary Class and Multi Class Strategies for Machine Learning
Binary Class and Multi Class Strategies for Machine LearningBinary Class and Multi Class Strategies for Machine Learning
Binary Class and Multi Class Strategies for Machine Learning
Paxcel Technologies
 
Biconnected components (13024116056)
Biconnected components (13024116056)Biconnected components (13024116056)
Biconnected components (13024116056)
Akshay soni
 
Complexity Analysis
Complexity Analysis Complexity Analysis
Complexity Analysis
Shaista Qadir
 
Introduction to Python Programing
Introduction to Python ProgramingIntroduction to Python Programing
Introduction to Python Programing
sameer patil
 

What's hot (20)

Introduction on Prolog - Programming in Logic
Introduction on Prolog - Programming in LogicIntroduction on Prolog - Programming in Logic
Introduction on Prolog - Programming in Logic
 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notations
 
Prims and kruskal algorithms
Prims and kruskal algorithmsPrims and kruskal algorithms
Prims and kruskal algorithms
 
Graphs bfs dfs
Graphs bfs dfsGraphs bfs dfs
Graphs bfs dfs
 
Rabin Carp String Matching algorithm
Rabin Carp String Matching  algorithmRabin Carp String Matching  algorithm
Rabin Carp String Matching algorithm
 
Prim's Algorithm on minimum spanning tree
Prim's Algorithm on minimum spanning treePrim's Algorithm on minimum spanning tree
Prim's Algorithm on minimum spanning tree
 
Depth First Search ( DFS )
Depth First Search ( DFS )Depth First Search ( DFS )
Depth First Search ( DFS )
 
Hierarchical clustering
Hierarchical clusteringHierarchical clustering
Hierarchical clustering
 
Asymptotic notation
Asymptotic notationAsymptotic notation
Asymptotic notation
 
Kruskal's algorithm
Kruskal's algorithmKruskal's algorithm
Kruskal's algorithm
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
 
Spanning trees
Spanning treesSpanning trees
Spanning trees
 
Analysis of algorithm
Analysis of algorithmAnalysis of algorithm
Analysis of algorithm
 
SINGLE-SOURCE SHORTEST PATHS
SINGLE-SOURCE SHORTEST PATHS SINGLE-SOURCE SHORTEST PATHS
SINGLE-SOURCE SHORTEST PATHS
 
Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures
 
Binary Class and Multi Class Strategies for Machine Learning
Binary Class and Multi Class Strategies for Machine LearningBinary Class and Multi Class Strategies for Machine Learning
Binary Class and Multi Class Strategies for Machine Learning
 
Biconnected components (13024116056)
Biconnected components (13024116056)Biconnected components (13024116056)
Biconnected components (13024116056)
 
Complexity Analysis
Complexity Analysis Complexity Analysis
Complexity Analysis
 
Introduction to Python Programing
Introduction to Python ProgramingIntroduction to Python Programing
Introduction to Python Programing
 

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

Unit ix graph
Unit   ix    graph Unit   ix    graph
Unit ix graph
Tribhuvan University
 
Unit 9 graph
Unit   9 graphUnit   9 graph
Unit 9 graph
Dabbal Singh Mahara
 
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
bashirabdullah789
 
lec 09-graphs-bfs-dfs.ppt
lec 09-graphs-bfs-dfs.pptlec 09-graphs-bfs-dfs.ppt
lec 09-graphs-bfs-dfs.ppt
TalhaFarooqui12
 
B.tech admission in india
B.tech admission in indiaB.tech admission in india
B.tech admission in india
Edhole.com
 
Chapter 23 aoa
Chapter 23 aoaChapter 23 aoa
Chapter 23 aoa
Hanif Durad
 
8.-Graphs information technologies graph
8.-Graphs information technologies graph8.-Graphs information technologies graph
8.-Graphs information technologies graph
iloveyoucarlo0923
 
Data Structures - Lecture 10 [Graphs]
Data Structures - Lecture 10 [Graphs]Data Structures - Lecture 10 [Graphs]
Data Structures - Lecture 10 [Graphs]
Muhammad Hammad Waseem
 
Unit 2: All
Unit 2: AllUnit 2: All
Unit 2: All
Hector Zenil
 
Graphs
GraphsGraphs
Graphs
Dwight Sabio
 
Graph ASS DBATU.pptx
Graph ASS DBATU.pptxGraph ASS DBATU.pptx
Graph ASS DBATU.pptx
ARVIND SARDAR
 
Graph
GraphGraph
Graph in data structure
Graph in data structureGraph in data structure
Graph in data structure
Pooja Bhojwani
 
Graph ds
Graph dsGraph ds
graph ASS (1).ppt
graph ASS (1).pptgraph ASS (1).ppt
graph ASS (1).ppt
ARVIND SARDAR
 
Graps 2
Graps 2Graps 2
6. Graphs
6. Graphs6. Graphs
6. Graphs
Mandeep Singh
 
Unit-6 Graph.ppsx ppt
Unit-6 Graph.ppsx                                       pptUnit-6 Graph.ppsx                                       ppt
Unit-6 Graph.ppsx ppt
DhruvilSTATUS
 
graph.pptx
graph.pptxgraph.pptx
graph.pptx
hijigaf
 
LEC 12-DSALGO-GRAPHS(final12).pdf
LEC 12-DSALGO-GRAPHS(final12).pdfLEC 12-DSALGO-GRAPHS(final12).pdf
LEC 12-DSALGO-GRAPHS(final12).pdf
MuhammadUmerIhtisham
 

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
 
Data Structures - Lecture 10 [Graphs]
Data Structures - Lecture 10 [Graphs]Data Structures - Lecture 10 [Graphs]
Data Structures - Lecture 10 [Graphs]
 
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
 

More from Md. Shafiuzzaman Hira

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

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

Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
Transcat
 
Levelised Cost of Hydrogen (LCOH) Calculator Manual
Levelised Cost of Hydrogen  (LCOH) Calculator ManualLevelised Cost of Hydrogen  (LCOH) Calculator Manual
Levelised Cost of Hydrogen (LCOH) Calculator Manual
Massimo Talia
 
Call Girls Chennai +91-8824825030 Vip Call Girls Chennai
Call Girls Chennai +91-8824825030 Vip Call Girls ChennaiCall Girls Chennai +91-8824825030 Vip Call Girls Chennai
Call Girls Chennai +91-8824825030 Vip Call Girls Chennai
paraasingh12 #V08
 
Determination of Equivalent Circuit parameters and performance characteristic...
Determination of Equivalent Circuit parameters and performance characteristic...Determination of Equivalent Circuit parameters and performance characteristic...
Determination of Equivalent Circuit parameters and performance characteristic...
pvpriya2
 
Blood finder application project report (1).pdf
Blood finder application project report (1).pdfBlood finder application project report (1).pdf
Blood finder application project report (1).pdf
Kamal Acharya
 
Butterfly Valves Manufacturer (LBF Series).pdf
Butterfly Valves Manufacturer (LBF Series).pdfButterfly Valves Manufacturer (LBF Series).pdf
Butterfly Valves Manufacturer (LBF Series).pdf
Lubi Valves
 
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
PriyankaKilaniya
 
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
nedcocy
 
EV BMS WITH CHARGE MONITOR AND FIRE DETECTION.pptx
EV BMS WITH CHARGE MONITOR AND FIRE DETECTION.pptxEV BMS WITH CHARGE MONITOR AND FIRE DETECTION.pptx
EV BMS WITH CHARGE MONITOR AND FIRE DETECTION.pptx
nikshimanasa
 
A high-Speed Communication System is based on the Design of a Bi-NoC Router, ...
A high-Speed Communication System is based on the Design of a Bi-NoC Router, ...A high-Speed Communication System is based on the Design of a Bi-NoC Router, ...
A high-Speed Communication System is based on the Design of a Bi-NoC Router, ...
DharmaBanothu
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
ydzowc
 
Sri Guru Hargobind Ji - Bandi Chor Guru.pdf
Sri Guru Hargobind Ji - Bandi Chor Guru.pdfSri Guru Hargobind Ji - Bandi Chor Guru.pdf
Sri Guru Hargobind Ji - Bandi Chor Guru.pdf
Balvir Singh
 
Height and depth gauge linear metrology.pdf
Height and depth gauge linear metrology.pdfHeight and depth gauge linear metrology.pdf
Height and depth gauge linear metrology.pdf
q30122000
 
Digital Image Processing Unit -2 Notes complete
Digital Image Processing Unit -2 Notes completeDigital Image Processing Unit -2 Notes complete
Digital Image Processing Unit -2 Notes complete
shubhamsaraswat8740
 
Transformers design and coooling methods
Transformers design and coooling methodsTransformers design and coooling methods
Transformers design and coooling methods
Roger Rozario
 
AI in customer support Use cases solutions development and implementation.pdf
AI in customer support Use cases solutions development and implementation.pdfAI in customer support Use cases solutions development and implementation.pdf
AI in customer support Use cases solutions development and implementation.pdf
mahaffeycheryld
 
Ericsson LTE Throughput Troubleshooting Techniques.ppt
Ericsson LTE Throughput Troubleshooting Techniques.pptEricsson LTE Throughput Troubleshooting Techniques.ppt
Ericsson LTE Throughput Troubleshooting Techniques.ppt
wafawafa52
 
Applications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdfApplications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdf
Atif Razi
 
AN INTRODUCTION OF AI & SEARCHING TECHIQUES
AN INTRODUCTION OF AI & SEARCHING TECHIQUESAN INTRODUCTION OF AI & SEARCHING TECHIQUES
AN INTRODUCTION OF AI & SEARCHING TECHIQUES
drshikhapandey2022
 
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
sydezfe
 

Recently uploaded (20)

Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
Tools & Techniques for Commissioning and Maintaining PV Systems W-Animations ...
 
Levelised Cost of Hydrogen (LCOH) Calculator Manual
Levelised Cost of Hydrogen  (LCOH) Calculator ManualLevelised Cost of Hydrogen  (LCOH) Calculator Manual
Levelised Cost of Hydrogen (LCOH) Calculator Manual
 
Call Girls Chennai +91-8824825030 Vip Call Girls Chennai
Call Girls Chennai +91-8824825030 Vip Call Girls ChennaiCall Girls Chennai +91-8824825030 Vip Call Girls Chennai
Call Girls Chennai +91-8824825030 Vip Call Girls Chennai
 
Determination of Equivalent Circuit parameters and performance characteristic...
Determination of Equivalent Circuit parameters and performance characteristic...Determination of Equivalent Circuit parameters and performance characteristic...
Determination of Equivalent Circuit parameters and performance characteristic...
 
Blood finder application project report (1).pdf
Blood finder application project report (1).pdfBlood finder application project report (1).pdf
Blood finder application project report (1).pdf
 
Butterfly Valves Manufacturer (LBF Series).pdf
Butterfly Valves Manufacturer (LBF Series).pdfButterfly Valves Manufacturer (LBF Series).pdf
Butterfly Valves Manufacturer (LBF Series).pdf
 
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
 
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
 
EV BMS WITH CHARGE MONITOR AND FIRE DETECTION.pptx
EV BMS WITH CHARGE MONITOR AND FIRE DETECTION.pptxEV BMS WITH CHARGE MONITOR AND FIRE DETECTION.pptx
EV BMS WITH CHARGE MONITOR AND FIRE DETECTION.pptx
 
A high-Speed Communication System is based on the Design of a Bi-NoC Router, ...
A high-Speed Communication System is based on the Design of a Bi-NoC Router, ...A high-Speed Communication System is based on the Design of a Bi-NoC Router, ...
A high-Speed Communication System is based on the Design of a Bi-NoC Router, ...
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
 
Sri Guru Hargobind Ji - Bandi Chor Guru.pdf
Sri Guru Hargobind Ji - Bandi Chor Guru.pdfSri Guru Hargobind Ji - Bandi Chor Guru.pdf
Sri Guru Hargobind Ji - Bandi Chor Guru.pdf
 
Height and depth gauge linear metrology.pdf
Height and depth gauge linear metrology.pdfHeight and depth gauge linear metrology.pdf
Height and depth gauge linear metrology.pdf
 
Digital Image Processing Unit -2 Notes complete
Digital Image Processing Unit -2 Notes completeDigital Image Processing Unit -2 Notes complete
Digital Image Processing Unit -2 Notes complete
 
Transformers design and coooling methods
Transformers design and coooling methodsTransformers design and coooling methods
Transformers design and coooling methods
 
AI in customer support Use cases solutions development and implementation.pdf
AI in customer support Use cases solutions development and implementation.pdfAI in customer support Use cases solutions development and implementation.pdf
AI in customer support Use cases solutions development and implementation.pdf
 
Ericsson LTE Throughput Troubleshooting Techniques.ppt
Ericsson LTE Throughput Troubleshooting Techniques.pptEricsson LTE Throughput Troubleshooting Techniques.ppt
Ericsson LTE Throughput Troubleshooting Techniques.ppt
 
Applications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdfApplications of artificial Intelligence in Mechanical Engineering.pdf
Applications of artificial Intelligence in Mechanical Engineering.pdf
 
AN INTRODUCTION OF AI & SEARCHING TECHIQUES
AN INTRODUCTION OF AI & SEARCHING TECHIQUESAN INTRODUCTION OF AI & SEARCHING TECHIQUES
AN INTRODUCTION OF AI & SEARCHING TECHIQUES
 
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
 

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