Graphs
Graphs
Part 1: Link
A Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes
also referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph. More
formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is denoted by
G(E, V).
Components of a Graph
Vertices: Vertices are the fundamental units of the graph. Sometimes, vertices are also known as vertex or
Edges: Edges are drawn or used to connect two nodes of the graph. It can be ordered pair of nodes in a
directed graph. Edges can connect any two nodes in any possible way. There are no rules. Sometimes,
Graphs are used to solve many real-life problems. Graphs are used to represent networks. The
networks may include paths in a city or telephone network or circuit network. Graphs are also used in
social networks like linkedIn, Facebook. For example, in Facebook, each person is represented with a
vertex(or node). Each node is a structure and contains information like person id, name, gender, locale
etc.
DFS and BFS
#include <bits/stdc++.h>
vector<bool> visited;
// preorder
visited[node] = true;
cout<<node<<" ";
if(visited[*it] == false)
dfs(*it, v);
// postorder
// cout<<node<<" ";
queue<int> pq;
pq.push(node);
visited[node] = true;
while(!pq.empty())
int t= pq.front();
pq.pop();
cout<<t<<" ";
if(visited[*it]);
else{
visited[*it] = true;
pq.push(*it);
int main()
int n, m;
vector<vector<int>> v(n);
{
int x, y;
cin>>x>>y;
v[x].push_back(y);
v[y].push_back(x);
dfs(0, v);
cout<<endl;
bfs(0, v);
return 0;
Best Problems on Graph (DFS/BFS)
Stepping Numbers
Bellman–Ford Algorithm
Dial’s Algorithm
Search in a Maze
Clone a graph
word Ladder
Dijkstra algo
Minimum time taken by each job to be completed given by a Directed Acyclic Graph
Find whether it is possible to finish all tasks or not from given dependencies
Find the no. of Isalnds
Implement Kruksal’sAlgorithm
Graph ColouringProblem
M-ColouringProblem
Minimise the cashflow among a given set of friends who have borrowed money from each
Shortest path to reach one prime to other by changing single digit at a time
Transpose graph
Bidirectional Search