Intro To Graphs - BFS and DFS
Intro To Graphs - BFS and DFS
● Maps
● Social media
● Computer Network
● SEAT - Course allocation!!
Some basic graph terminology
● If we traverse a graph such that we do not repeat a vertex and nor we repeat
an edge from one vertex(source) to another(destination), then the sequence
of edges is called is called a path from the source to destination.
● Edges are usually denoted by a pair of the vertices which it connects (A,B)
● In a directed graph one can move along one direction only along a unique
edge.For eg in a directed graph edge (A,B) -we can move from A to B but not B
to A.
● In an undirected graph one can move in both directions
Some Important Points
● Minimum distance?
○ Not so fast!!
Problems
● Party
● Counting Rooms
● Building Roads
BFS - Breadth First Search root
1
● Breadth-first search (BFS) follows an 3
approach different from depth first 2
search. 4 5 7
● BFS visits the nodes in increasing order
6
of their distance from the starting
node. 8
● We can calculate the minimum
distance from the starting node to all
other nodes using breadth-first search.
BFS - Breadth First Search
● Breadth-first search goes through the
nodes one level after another. First the
search explores the nodes whose
distance from the starting node is 1,
then the nodes whose distance is 2,
and so on. This process continues until
all nodes have been visited.
How to BFS?
queue<int> q;
int visited[n]={0};
q.push(root);
visited[root]=1;
while(!q.empty())
{
int cur=q.front();
q.pop();
for(int i=0;i<g[cur].size();i++)
{
if(!visited[g[cur][i]])
{
visited[g[cur][i]]=1;
q.push(g[cur][i]);
}
}
}
Collecting each depth nodes
vector<int>itr;
int visited[n]={0};
itr.push_back(root);
visited[root]=1;
while(!itr.empty())
{
vector<int>nitr;
for(int i:itr)
{
for(auto j:g[i])
if(!visited[j])
{
visited[j]=1;
nitr.push_back(j);
}
}
itr=nitr;
}
What can we solve now?
● Minimum distance?
○ Yes, do a BFS from i, store depth as distance.
Blitztage doesn't want to waste the money of the country, so he is going to close some of the
roads. Please tell Blitztage the maximum number of the train routes which can be closed under
the following condition: the length of the shortest path from every city to the capital mustn't
change.
In-time and out-time
● In-time: Time at which we enter the node
● Out-time: Time at which we exit the node
In-time: Out-time:
A- 1 F- 7 A- 18 F- 8
B- 2 G- 12 B- 9 G- 13
C- 10 H- 14 C- 17 H- 15
D- 11 I- 4 D- 16 I- 5
E- 3 E- 6
Edge types and Ancestor
● Ancestor: x is ancestor of y if we enter y after entering x and exit y before
exiting x.
● Tree edge: The edge we traversed while doing dfs.
● Forward edge: If the edge is from ancestor to child and not tree edge.
● Back edge: If the edge is from child to ancestor.
● Cross edge: All other