0% found this document useful (0 votes)
87 views24 pages

Intro To Graphs - BFS and DFS

The document discusses graphs and graph algorithms breadth-first search (BFS) and depth-first search (DFS). It defines what a graph is - entities as vertices and relationships between entities as edges. It provides examples of real-world problems that can be modeled as graphs like maps and social networks. It then explains some basic graph terminology and how graphs can be stored. The document also introduces trees as a special type of graph and provides examples of problems that can be solved using BFS and DFS.

Uploaded by

Girish Sai Adapa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views24 pages

Intro To Graphs - BFS and DFS

The document discusses graphs and graph algorithms breadth-first search (BFS) and depth-first search (DFS). It defines what a graph is - entities as vertices and relationships between entities as edges. It provides examples of real-world problems that can be modeled as graphs like maps and social networks. It then explains some basic graph terminology and how graphs can be stored. The document also introduces trees as a special type of graph and provides examples of problems that can be solved using BFS and DFS.

Uploaded by

Girish Sai Adapa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

WPC-2022

S4: Intro to Graph, BFS & DFS


What is Graph?

● It is a structure to represent relationships among entities in our problem.


● These entities eg people, junctions/cities on a road map etc- Vertices
● The Relationships connecting these entities Eg friendship between two
people or the road connecting two cities- Edges
Why Graph?
Many problems in real life are effectively modeled by graphs.

● Maps
● Social media
● Computer Network
● SEAT - Course allocation!!
Some basic graph terminology

● Vertex and edge


● Path and connectedness
● Directed or Undirected
● Vertex weighted, edge weighted
Some Basic Terms

● 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

● A graph is called connected if there exists a path between every pair of


vertices
● If the graph is unconnected , the maximum subgraphs which are connected
are called components
● If there exists a path having positive number of edges from one vertex to
itself, then the path is called cycle. The graph is then said to have a cycle
● Some problems might have graphs were the vertices and edges are different
in properties from each other-in that case we give weights to them-eg flight
charges for two different pairs is different.
How to store graphs?
● Majorly stored in 2 ways,
○ 1) Adjacency matrix
○ 2) Adjacency list

● We will mostly be using


adjacency list as it takes less
space and it is more efficient
to find all neighbours of a
vertex.
How to store graphs in program?
int n,m; int n,m;
int g[n][n]; vector<int> g[n];
for(int i=0;i<n;i++) for(int i=0;i<m;i++)
{ {
for(int j=0;j<n;j++) int x,y;
g[i][j]=0; cin>>x>>y;
} g[x].push_back(y);
// g[y].push_back(x);
for(int i=0;i<m;i++) }
{
int x,y;
cin>>x>>y;
g[x][y]=1;
List
}
// g[y][x]=1; If undirected graph Matrix
Trees - Special type of graph

● A connected graph with no cycle.


● If n vertices then will have n-1 edges.
● Most of the questions in CP are based on
trees.
Some example problems
● n cities connected by m roads, you are on city i currently, can you
reach city j?
● How many minimum roads you need to travel?
● Can you reach all cities from i?
● If distance to a city j is defined as minimum road you need to travel
from city i to reach j, then what is maximum distance of any city?
● Each road has some tax associated with it, what is minimum cost of
going through all cities starting at i?
DFS - Depth First Search
● Depth-first search (DFS) is a recursive
algorithm which starts at the root node
(selecting some arbitrary node as the
root node in the case of a graph) and
explores for unvisited vertices as far as
possible along each branch before
backtracking.
● This path need not be the shortest path
to the root.
How to DFS?
void dfs(vector<int>g[], int cur, int visited[])
{ Just after entering
// Position 1
for(int i=0;i<g[cur].size();i++)
{
if(!visited[g[cur][i]])
{ Just before entering
// Position 2
visited[g[cur][i]]=1;
cout<<cur<<" "<<g[cur][i]<<endl;
dfs(g,g[cur][i],visited); Just after exiting
// Position 3
}
} Just before exiting
// Position 4
}
What can we solve now?
● Do a dfs from city i.

● Is city j reachable from city i:


○ Check if visited[j] true at the end.

● Are all cities reachable?


○ Check if all visited are true.

● 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.

● What is each of edges have a weight?


○ This is called a weighted graph, normal BFS does not work, we
will learn shortest path algorithms tomorrow.
Example Problem
● Checking if a graph is connected
● Chessboard Knight Problem
● Problem - 580C - Codeforces
Example problem
Blitztage is the president of country A. There are n cities numbered from 1 to n in his country.
City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to
vi (and vise versa) using the i-th road.

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

You might also like