Vertices,edges,undirected and directed graph,cyclic & acyclic graph,degree indegree & outdegree and weights. In an undirected graph, the sum of degrees of all vertices is double the vertices (We consider degree=indegree=outdegree in an undirected graph).
Graph representation in C++
Let us say there are n nodes and m edges. And adj[i][j] represents there is an edge from node i to j.
There are two ways to represent a graph
1. Adjacency matrix:
code
int n, m;
cin >> n >> m;
int adj[n+1][n+1]; //1 based indexing
for(int i = 0;i<m;i++) {
int u, v;
cin >> u >> v;
adj[u][v] = 1;
adj[v][u] = 1; //write this line only if the graph is undirected
}
Time Complexity:O(m)**** Space Complexity:**O(n*n)**
2. Adjacency List
codeint n,m;
cin >> n >> m;
vector<vector<int> > adj(n+1);
for(int i = 0;i<m;i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u); //undirected graph
}
return 0;
}
Time Complexity:**O(m)** Space Complexity:**O(n*n)**
If there are also weights in edges, we create the adjacency list as ' vector <vector < pair <int,int> > > ' where first value is node(v) and second value represents weight b/w the nodes(u and v).
Since there can be multiple disconnected components in a graph, while graph traversal we have to call BFS/DFS from every unvisited node. To avoid repetition we store information if a node is visited or not by creating a boolean array where is_visited[i]==true represents node 'i' is visited.
for(int i=1i<=n;i++)
{
if(!is_visited[i]) BFS(i);
}
BFS
codefor(int i=0;i<n;i++)
{
if(!vis[i])
{
queue<int> q;
q.push(i);
vis[i] = 1;
while(!q.empty())
{
int node = q.front();
q.pop();
cout<<node<<" ";
for(auto child : adj[node])
{
if(!vis[child])
{
q.push(child);
vis[child] = 1;
}
}
}
}
}
Time Complexity:**O(n+e)** ( O(n+e): n time taken for visiting n nodes and e time taken for traversing through adjacent nodes)
Space Complexity:**O(n)** ( O(n) for visiting array and O(n) for queue )
DFS
codevoid dfs(int node, vector<bool> &vis,vector <vector <int> > &adj)
{
cout<<node<<" ";
vis[node]=1;
for(auto child : adj[node])
{
if(!vis[child])
{
dfs(child,vis,adj);
}
}
}
//Inside main()
for(int i = 1;i<=V;i++)
{
if(!vis[i])
dfs(i, vis, adj);
}
Time Complexity:**O(n+e)** ( O(n+e): n time taken for visiting n nodes and e time taken for traversing through adjacent nodes)
Space Complexity:**O(n)** ( O(n) for visiting array and O(n) for stack space )
Cycle Detection in Graphs
Case 1: Cycle detection in undirected graph using dfs
If a node adjacent to a node ( that is not its parent node ) is already visited, the component contains a cycle.
codebool checkForCycle_DFS(int node, int parent, vector<int> &vis, vector <vector<int> > &adj)
{
vis[node] = 1;
for(auto child:adj[node])
{
if(vis[child]&&child!=parent) return true;
if(!vis[child])
{
if(checkForCycle_DFS(child, node, vis, adj)) return true;
}
}
return false;
}
//Inside main()
for(int i = 0;i<n;i++)
{
if(!vis[i])
{
if(checkForCycle_DFS(i, -1, vis, adj)) return true;
}
}
return false;
Case 2:Cycle detection in the undirected graph using BFS
codecheckCycle_BFS(int node, int parent, vector<bool> &vis, vector <vector<int> > &adj)
{
vis[i]=1;
queue<pair <int,int> > q;
q.push({i,-1});
while(!q.empty())
{
int node = q.front().first;
int parent=q.front().second;
q.pop();
for(auto child : adj[node])
{
if(vis[child]&&child!=parent) return true;
if(!vis[child])
{
q.push({child,node});
vis[child] = 1;
}
}
}
return false;
}
//Inside main()
for(int i=0;i<n;i++)
{
if(!vis[i])
{
if(checkCycle_BFS(i,-1,vis,adj)) return true;
}
}
return false;
Case 3:Cycle detection in the Directed graph using DFS-
codebool checkForCycle_DFS(int node, int parent, vector<int> &color, vector <vector<int> > &adj)
{
color[node] = 1;
for(auto child:adj[node])
{
if(color[child]==1&&child!=parent) return true;
if(!color[child])
{
if(checkForCycle_DFS(child, node, color, adj)) return true;
}
}
color[node]=2;
return false;
}
//Inside main()
for(int i = 0;i<n;i++)
{
if(!vis[i])
{
if(checkForCycle_DFS(i, -1, vis, adj)) return true;
}
}
return false;
Case 3:Cycle detection in the Directed graph using BFS
Assume the directed graph to be acyclic i.e. DAG and find its topological order.If we can do topological sorting i.e. pushing all nodes in queue , the graph is acyclic,other wise it is cyclic.
We increase our count by 1 (starting from 0) each time we push a node in queue. And if final value of count==no. of nodes in graph, the graph is a DAG.
code//The given code is for one component graph.
//You can find topological order for multiple component graph using vis array.
bool isCyclic(int N, vector<int> adj[])
{
queue <int> q;
vector <int> indegree(N, 0);
for(int i = 0;i<N;i++)
{
for(auto it: adj[i])
indegree[it]++;
}
for(int i = 0;i<N;i++)
{
if(indegree[i] == 0)
q.push(i);
}
int cnt = 0;
while(!q.empty())
{
int node = q.front();
q.pop();
cnt++;
for(auto it : adj[node])
{
indegree[it]--;
if(indegree[it] == 0)
q.push(it)
};
}
if(cnt == N) return false;
return true;
}
Bipartite graph:
A graph will not be a bipartite iff it has a cycle with an odd no. of nodes.
Check whether a graph is bipartite or not using BFS
codebool bipartiteBFS(int src, vector <vector<int> > &adj, int color[])
{
color[src] = 1;
queue<int> q;
q.push(src);
while(!q.empty())
{
int node = q.front();
q.pop();
for(auto child : adj[node])
{
if(color[child] == color[node])
{
return false;
}
else if(color[child] == -1)
{
color[child] = 1 - color[node];
q.push(child);
}
}
}
return true;
}
//Inside main()
for(int i = 0;i<n;i++)
{
if(color[i] == -1)
{
if(!bipartiteBFS(i, adj, color)) return false;
}
}
return true;
Check whether a graph is bipartite or not using DFS
codebool bipartiteDfs(int node, vector <vector<int> > &adj, int color[])
{
for(auto child : adj[node])
{
if(color[child] == color[node]) return false;
else if(color[child] == -1)
{
color[child] = 1 - color[node];
if(!bipartiteDfs(child, adj, color))
{
return false;
}
}
}
return true;
}
//Inside main()
for(int i = 0;i<n;i++)
{
if(color[i] == -1)
{
color[i] = 1;
if(bipartiteDfs(i, adj, color)==false) return false;
}
}
return true;
Topological Sorting:
Only possible in DAG. It is a linear order of vertices such that for every directed edge u-->v, vertex u comes before v in that order. A DAG has at least one node with indegree=0.
Topological sorting using BFS
First, calculate indegree of all nodes and store it in vector.Then push all nodes with degree==0 in a queue.Take each node one by one out of queue and for all its child ,decrease their indegree by 1. After this if any child has indegree==0, push them in the queue.
code//The given code is for one component graph.
//You can find topological order for multiple component graph by calling this func for every unvisited node.
vector<int> findTopo(int N,vector < vector <int> > &adj)
{
vector<int> indegree(N, 0);
for(int i = 0;i<N;i++)
for(auto it: adj[i])
indegree[it]++;
queue<int> q;
for(int i = 0;i<N;i++)
{
if(indegree[i] == 0) q.push(i);
}
vector<int> topo;
while(!q.empty())
{
int node = q.front();
q.pop();
topo.push_back(node)
for(auto child : adj[node])
{
indegree[child]--;
if(indegree[child] == 0)
q.push(child);
}
}
return topo;
}
Topological sorting using DFS
Topological order is the order of nodes in decreasing order of finishing time i.e. the node that gets finished at last comes first in order.
code//The given code is for one component graph.
//You can find topological order for multiple component graph by calling this func for every unvisited node.
void findTopoSort(int node, vector<int> &vis, stack<int> &st, vector<int> adj[])
{
vis[node] = 1;
for(auto it : adj[node])
{
if(!vis[it])
findTopoSort(it, vis, st, adj);
}
st.push(node);
}
Shortest path algorithms:
Shortest path of all nodes from a node in a uni-weighted undirected graph.
Use BFS for this because BFS visits nodes in a sequential manner. That is nodes at the same level are visited simultaneously. Run BFS and equate dist[node] = 1+dist[parent].
codevoid BFS(vector<int> adj[], int N, int src)
{
int dist[N];
dist[src] = 0;
for(int i = 1;i<N;i++) dist[i] = INT_MAX;
queue<int> q;
q.push(src);
while(q.empty()==false)
{
int node = q.front();
q.pop();
for(auto it:adj[node])
{
//no use of vis array because if a dist[node] is relaxed,
//it implies it is being visited first time.
if(dist[node] + 1 < dist[it])
{
dist[it]=dist[node]+1;
q.push(it);
}
}
}
for(int i = 0;i<N;i++) cout << dist[i] << " ";
}
Shortest path of all nodes from a node in a weighted DAG
The weights can be -ve.
Minimum sum to reach a node 'v' i.e. dist[v] is minimum of all (dist[u]+weight(u-->v)),where u is node from all its parents. Similarly, dist[u] is calculated with the help of its parents.We can observe that ultimately we have to start calculating dist[] from source node and in topological order ,we have to visit the nodes
We visit nodes in topological order and relax all its children. In this way, each node is relaxed by all its parents.
codevoid shortestPath(int src, int N, vector<pair<int,int>> &adj)
{
int vis[N] = {0};
stack<int> st;
for (int i = 0; i < N; i++)
if(!vis[i])
findTopoSort(i, vis, st, adj);
int dist[N];
for (int i = 0; i < N; i++)
dist[i] = 1e9;
dist[src] = 0;
while(!st.empty())
{
int node = st.top();
st.pop();
if (dist[node] != INF)
{
for(auto child : adj[node])
{
if(dist[node] + .second < dist[child.first])
dist[child.first] = dist[node] + child.second;
}
}
}
for (int i = 0; i < N; i++)
(dist[i] == 1e9)? cout<< "INF ": cout << dist[i] << " ";
}
Shortest path in +ve weighted graph.
Dijkstra's algorithm is basically an efficient version of breadth-first search on a different graph.
Given a graph G with positive integer edge-weights, one could construct a new unweighted graph H, by replacing each weighted edge with a number of edges equivalent to its weight. So, for example, if you had an edge (u,v) with weight 10 in G, you'd replace this edge with a series of 10 edges between u and v.
Since BFS visits nodes in increasing order of their level (distance from source node) i.e. at any point of time,if a node n1 level is smaller than node n2, minimum distance from n1 will be calculated earlier than n2.
From this, we get an intuition that at any point of time, calculate minimum distance of children of that node which is nearest to the source node. This is a kind of greedy approach because we are relaxing children of that node which is locally(at a point of time) nearest to the source.
Since min_priority_queue always stores elements in increasing order,we will use it.
codetypedef pair<int, int> pi;
vector <int> dijkstra(int n,vector<vector<pi>> &adj, int s)
{
priority_queue<pi, vector<pi>, greater<pi> > pq;
//min heap (weight,node)
vector <int> dist(n);
for(int i=0; i<n; i++) dist[i]=1e9;
dist[s]=0;
pq.push({dist[s], s});
while (!pq.empty())
{
int u=pq.top().second;
pq.pop();
for(auto p: adj[u])
{
int v=p.first;
int w=p.second;
if(dist[u] + w < dist[v])
{
dist[v] =dist[u] + w;
pq.push({dist[v], v});
}
}
}
return dist;
}
Why djikstra doesn't work with -ve weights:
If all weights are non-negative, adding an edge can never make a path shorter but this is not valid if edge weight is -ve. .Dry run a case to explain it further