0% found this document useful (0 votes)
2 views

Graph code

The document provides various C++ algorithms for detecting cycles in both directed and undirected graphs using Depth-First Search (DFS) and Breadth-First Search (BFS). It also includes implementations for finding the shortest path in unweighted graphs, Dijkstra's algorithm using both a 2D array and an adjacency list, and solving problems related to minimum steps for a knight and minimum jumps to reach the end of an array. Additionally, it discusses finding the number of islands in a grid using DFS.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Graph code

The document provides various C++ algorithms for detecting cycles in both directed and undirected graphs using Depth-First Search (DFS) and Breadth-First Search (BFS). It also includes implementations for finding the shortest path in unweighted graphs, Dijkstra's algorithm using both a 2D array and an adjacency list, and solving problems related to minimum steps for a knight and minimum jumps to reach the end of an array. Additionally, it discusses finding the number of islands in a grid using DFS.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

 Detect cycle in directed graph using DFS

// A C++ Program to detect cycle in a directed graph


#include<bits/stdc++.h>

using namespace std;

int V; // No. of vertices


map<int,list<int>> adj;

void addEdge(int v, int w)


{
adj[v].push_back(w); // Add w to v’s list.
}

bool dfs(int v, vector<bool> &vis,vector<bool> &rs)


{
if(vis[v] == false)
{
vis[v] = true;
rs[v] = true;

for(auto i: adj[v])
{
//cout<<v<<" - "<<i<<" Before "<<rs[i]<<endl;
if ( !vis[i] && dfs(i, vis, rs) ) {
//cout<<v<<" - "<<i<<endl;
return true;
}
//cout<<rs[i]<<" After"<<endl;
else if (rs[i]) {
cout<<v<<" rs- "<<i<<endl;
return true;
}
}
}
rs[v] = false; // remove the vertex from recursion stack
return false;
}

// Returns true if the graph contains a cycle, else false.


bool isCyclic()
{
vector<bool> vis(V,false);
vector<bool> recStack(V,false);
for(int i = 0; i < V; i++)
if ( !vis[i] && dfs(i, vis, recStack))
return true;

return false;
}

int main()
{

V=4;
addEdge(0, 1);
addEdge(0, 2);
addEdge(1, 2);
addEdge(2, 0);
addEdge(2, 3);
addEdge(3, 3);

if(isCyclic())
cout << "Graph contains cycle";
else
cout << "Graph doesn't contain cycle";
return 0;
}

 Detect Cycle in an Undirected Graph using DFS


// A C++ Program to detect cycle in an undirected graph
#include<bits/stdc++.h>
using namespace std;

int V; // No. of vertices


map<int,list<int>> adj; // Pointer to an array containing adjacency lists

void addEdge(int v, int w)


{
adj[v].push_back(w); // Add w to v’s list.
adj[w].push_back(v);
}

bool dfs(int v, vector<bool> &vis,int parent)


{
vis[v] = true;

for(auto i: adj[v])
{
if ( !vis[i]){
if(dfs(i, vis, v)) {
return true;
}}
//cout<<rs[i]<<" After"<<endl;
else if (i!=parent) {
cout<<v<<" rs- "<<i<<endl;
return true;
}
}
return false;
}

// Returns true if the graph contains a cycle, else false.


bool isCyclic()
{
vector<bool> vis(V,false);

for(int i = 0; i < V; i++)


if (!vis[i]) if( dfs(i, vis, -1))
return true;

return false;
}

int main()
{
V=5;
addEdge(1, 0);
addEdge(0, 2);
addEdge(2, 1);
addEdge(0, 3);
addEdge(3, 4);
isCyclic() ? cout << "Graph contains cycle\n"
: cout << "Graph doesn't contain cycle\n";

adj.clear();
V=3;
addEdge(0, 1);
addEdge(1, 2);
//addEdge(2, 0);
isCyclic() ? cout << "Graph contains cycle\n"
: cout << "Graph doesn't contain cycle\n";
return 0;
}

 Detect cycle in directed graph using BFS


// Online C++ compiler to run C++ program online
#include <bits/stdc++.h>
using namespace std;

int V;
map<int,list<int>> adj;

void addEdge(int u,int v){


adj[u].push_back(v);
}

bool isCycle(){
int cnt=1;

vector<int> indeg(V,0);
for(int i=0;i<V;i++){
for(auto a:adj[i]) indeg[a]++;
}

queue<int> q;
for(int i=0;i<V;i++)
if(indeg[i]==0) {q.push(i);cout<<i<<endl;}

while(!q.empty()){
int temp=q.front();
q.pop();
for(int a:adj[temp])
{
if(--indeg[a]==0) { q.push(a);cnt++;}
}
}
cout<<cnt<<endl;
if(cnt!=V) return true;
else return false;

}
int main()
{
// Create a graph given in the above diagram
V=6;
addEdge(0, 1);
addEdge(1, 2);
addEdge(2, 3);
addEdge(3, 4);
addEdge(4, 5);
//addEdge(5, 4);
if (isCycle())
cout << "Yes";
else
cout << "No";

return 0;
}

 Detect Cycle in an Undirected Graph using BFS


 Shortest path in an unweighted graph
// CPP code for printing shortest path between
// two vertices of unweighted graph
#include <bits/stdc++.h>
using namespace std;

map<int,list<int>> adj;

void add_edge(int src, int dest)


{
adj[src].push_back(dest);
adj[dest].push_back(src);
}

bool bfs(int src,int dest,int v,vector<int> &dist,vector<int> &pred){


vector<int> vis(v,0);
queue<int> q;
q.push(src);
vis[src]=1;
while(!q.empty()){
int temp=q.front();
q.pop();
for(auto a:adj[temp])
{
if(!vis[a]){
q.push(a);
vis[a]=1;
dist[a]=dist[temp]+1;
pred[a]=temp;
if(a==dest) return true;
}
}
}
return false;
}

void printShortestDistance(int src,int dest,int v){


vector<int> dist(v,INT_MAX);
vector<int> pred(v,-1);
dist[src]=0;
if(bfs(src,dest,v,dist,pred)== false){
cout<<"Not connected"<<endl;
return;
}
vector<int> path;
path.push_back(dest);
int x=dest;
while(x!=src){
path.push_back(pred[x]);
x=pred[x];
}
for(int i=path.size()-1;i>=0;i--){
cout<<path[i]<<"->";
}
}

int main()
{
int v = 8;

add_edge(0, 1);
add_edge(0, 3);
add_edge(1, 2);
add_edge(3, 4);
add_edge(3, 7);
add_edge(4, 5);
add_edge(4, 6);
add_edge(4, 7);
add_edge(5, 6);
add_edge(6, 7);
int source = 0, dest = 7;
printShortestDistance(source, dest, v);
return 0;
}

 Dijkstra Algorithm with 2d array graph


#include <bits/stdc++.h>
using namespace std;

#define V 9
int shortdist(vector<int> dist,vector<bool> spt){
int minm=INT_MAX,index;
for(int i=0;i<V;i++){
if(!spt[i] && dist[i]<=minm)
minm=dist[i],index=i;
}
return index;
}
void dijkstra(int graph[V][V],int src){
vector<int> dist(V,INT_MAX);
vector<bool> spt(V,false);
dist[src]=0;
for(int i=0;i<V;i++){
int u=shortdist(dist,spt);
spt[u]=true;
for(int j=0;j<V;j++){
if(graph[u][j] && !spt[j] && dist[u]!=INT_MAX && dist[u]+graph[u][j]<dist[j])
dist[j]=dist[u]+graph[u][j];
}
}
for(int i=0;i<V;i++){
cout << i << " \t\t"<<dist[i]<< endl;
}
}
int main()
{
int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };

dijkstra(graph, 0);
return 0;
}
 Dijkstra using adjacency list
#include <bits/stdc++.h>
using namespace std;

#define V 9
typedef pair<int,int> pa;

map<int,list<pa> adj;
void addEdge(int u,int v,int value){
adj[u].push_back(make_pair(v,value));
adj[v].push_back(make_pair(u,value));
}

void dijkstra(int src){


vector<int> dist(V,INT_MAX);
vector<bool> spt(V,false);
dist[src]=0;
priority_queue< pa,vector<pa>,greater<pa> > minh;
minh.push(make_pair(dist[src],src));
for(int i=0;i<V;i++){
pa p=minh.top();
int u=p.second;
minh.pop();
spt[u]=true;
for(auto c:adj[u]){
if(dist[u]!=INT_MAX && !spt[c.first] && dist[u]+c.second<dist[c.first])
dist[c.first]=dist[u]+c.second,minh.push(make_pair(dist[c.first],c.first));
}
}

for(int i=0;i<V;i++){
cout << i << " \t\t"<<dist[i]<< endl;
}
}
int main()
{
addEdge(0, 1, 4);
addEdge(0, 7, 8);
addEdge(1, 2, 8);
addEdge(1, 7, 11);
addEdge(2, 3, 7);
addEdge(2, 8, 2);
addEdge(2, 5, 4);
addEdge(3, 4, 9);
addEdge(3, 5, 14);
addEdge(4, 5, 10);
addEdge(5, 6, 2);
addEdge(6, 7, 1);
addEdge(6, 8, 6);
addEdge(7, 8, 7);

dijkstra(0);
return 0;
}

 Minimum steps to reach target by a Knight


#include <bits/stdc++.h>
using namespace std;

struct cell {
int x, y,dis;
cell() {}
cell(int x, int y, int dis)
: x(x), y(y), dis(dis)
{
}
};

bool isInside(int x, int y, int N)


{
if (x >= 1 && x <= N && y >= 1 && y <= N)
return true;
return false;
}

int minStepToReachTarget(
int knightPos[], int targetPos[],
int N)
{
int dx[] = { -2, -1, 1, 2, -2, -1, 1, 2 };
int dy[] = { -1, -2, -2, -1, 1, 2, 2, 1 };

queue<cell> q;
q.push(cell(knightPos[0], knightPos[1], 0));

cell t;
int x, y;
vector<vector<bool> > visit(N+1,vector<bool>(N+1,false));

visit[knightPos[0]][knightPos[1]] = true;

while (!q.empty()) {
t = q.front();
q.pop();
if (t.x == targetPos[0] && t.y == targetPos[1])
return t.dis;

for (int i = 0; i < 8; i++) {


x = t.x + dx[i];
y = t.y + dy[i];

if (isInside(x, y, N) && !visit[x][y]) {


visit[x][y] = true;
q.push(cell(x, y, t.dis + 1));
}
}
}
}

int main()
{
int N = 30;
int knightPos[] = { 1, 1 };
int targetPos[] = { 30, 30 };
cout << minStepToReachTarget(knightPos, targetPos, N);
return 0;
}
 Minimum number of jumps to reach end
#include <bits/stdc++.h>
using namespace std;

int minJumps( vector<int> &arr,int n){


if(n==1) return 0;
// for(int i=n-2;i>=0;i--){
// if(i+arr[i]>=n-1){
// int temp=minJumps(arr,i+1);
// if(temp!=INT_MAX)
// ans=min(ans,temp+1);
// }
// }
vector<int> jump(n,INT_MAX);
jump[0]=0;
for(int i=0;i<n;i++){
for(int j=i+1;j<i+1+arr[i] && j<n;j++){
if(jump[i]!=INT_MAX)
jump[j]=min(jump[j],jump[i]+1);
}
}
if(jump[n-1]==INT_MAX) jump[n-1]=0;
return jump[n-1];
}
int main()
{
vector<int> arr= {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
int n = arr.size();
cout << "Minimum number of jumps to";
cout << " reach the end is " << minJumps(arr, n);
return 0;
}
 Minimum number of jumps to reach end (Optimised O(n))
#include <bits/stdc++.h>
using namespace std;

int minJumps(int arr[], int n){


if(n<=1) return 0;
if(arr[0]==0) return 0;
int maxReach=arr[0];
int step=arr[0];
int jump=1;
for(int i=1;i<n;i++){
if(i==n-1) return jump;
maxReach=max(maxReach,i+arr[i]);
step--;
if(step==0){
jump++;
if(i>=maxReach) return -1;
step=maxReach-i;
}
}
return -1;
}
int main()
{
int arr[] = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 };
int size = sizeof(arr) / sizeof(int);

cout << ("Minimum number of jumps to reach end is %d ",


minJumps(arr, size));
return 0;
}
 Find the number of islands (Using DFS)
#include <bits/stdc++.h>
using namespace std;

#define row 5
#define col 5

int dx[]={ -1, -1, -1, 0, 1, 1, 1, 0 };


int dy[]={ -1, 0, 1, 1, 1, 0, -1, -1 };

bool valid(int x,int y){


if(x>=0 && x<col && y>=0 && y<col) return true;
return false;
}
void dfs(int M[][col],vector<vector<int> > &vis,int x,int y){
vis[x][y]=true;
for(int i=0;i<8;i++){
int x1=x+dx[i];
int y1=y+dy[i];
if(valid(x1,y1) && M[x1][y1] && !vis[x1][y1]) dfs(M,vis,x1,y1);
}
}
int countIslands(int M[][col]){
vector<vector<int> > vis(row,vector<int>(col,false));
int cnt=0;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(!vis[i][j] && M[i][j]) {
dfs(M,vis,i,j);
cnt++;
}
}
}
return cnt;
}
int main()
{
int M[][col] = { { 1, 1, 0, 0, 0 },
{ 0, 1, 0, 0, 1 },
{ 1, 0, 0, 1, 1 },
{ 0, 0, 0, 0, 0 },
{ 1, 0, 1, 0, 1 } };

cout << "Number of islands is: " << countIslands(M);

return 0;
}
 Bridges in a graph
We do DFS traversal of the given graph. In DFS tree an edge (u, v) (u is parent of v in DFS tree) is bridge if
there does not exist any other alternative to reach u or an ancestor of u from subtree rooted with v.
The value low[v] indicates earliest visited vertex reachable from subtree rooted with v. The condition for
an edge (u, v) to be a bridge is, “low[v] > disc[u]”.

#include<bits/stdc++.h>
using namespace std;

int V;
map<int,list<int> > adj;
int tme = 1;
void addEdge(int v, int w)
{
adj[v].push_back(w);
adj[w].push_back(v);
}

void bridgeUtil(int u, vector<bool> &vis, vector<int> &disc,


vector<int> &low, vector<int> &parent)
{
vis[u] = true;
disc[u] = low[u] = tme++;
for (auto v:adj[u])
{
if (!vis[v])
{
parent[v] = u;
bridgeUtil(v, vis, disc, low, parent);
low[u] = min(low[u], low[v]);
if (low[v] > disc[u])
cout << u <<" " << v << endl;
}
else if (v != parent[u])
low[u] = min(low[u], disc[v]);
}
}
void bridge()
{
vector<bool> vis(V,false);
vector<int> disc(V);
vector<int> low(V);
vector<int> parent(V,-1);

for (int i = 0; i < V; i++)


if (vis[i] == false)
bridgeUtil(i, vis, disc, low, parent);
}

int main()
{
cout << "\nBridges in first graph \n";
V=5;
addEdge(1, 0);
addEdge(0, 2);
addEdge(2, 1);
addEdge(0, 3);
addEdge(3, 4);
bridge();
adj.clear();

cout << "\nBridges in second graph \n";


V=4;
tme=1;
addEdge(0, 1);
addEdge(1, 2);
addEdge(2, 3);
bridge();
adj.clear();

cout << "\nBridges in third graph \n";


V=7;
tme=1;
addEdge(0, 1);
addEdge(1, 2);
addEdge(2, 0);
addEdge(1, 3);
addEdge(1, 4);
addEdge(1, 6);
addEdge(3, 5);
addEdge(4, 5);
bridge();
adj.clear();

return 0;
}
 Topological Sorting
#include <bits/stdc++.h>
using namespace std;

int V;
map<int,list<int> > adj;

void addEdge(int u, int v){


adj[u].push_back(v);
}

void topologicalSortUtil(int u, vector<bool> &vis, stack<int> &stk)


{
vis[u] = true;

for (auto v:adj[u])


if (!vis[v])
topologicalSortUtil(v, vis, stk);

stk.push(u);
}

void topologicalSort()
{
stack<int> stk;
vector<bool> vis(V,false);

for (int i = 0; i < V; i++)


if (!vis[i])
topologicalSortUtil(i, vis, stk);

while (!stk.empty()) {
cout << stk.top() << " ";
stk.pop();
}
}

int main()
{
V=6;
addEdge(5, 2);
addEdge(5, 0);
addEdge(4, 0);
addEdge(4, 1);
addEdge(2, 3);
addEdge(3, 1);
cout << "Following is a Topological Sort of the given "
"graph \n";

topologicalSort();
return 0;
}
 Given a sorted dictionary of an alien language, find order of characters
#include <bits/stdc++.h>
using namespace std;

int V;
map<int,list<int> > adj;

void addEdge(int u, int v){


adj[u].push_back(v);
}

void topologicalSortUtil(int u, vector<bool> &vis, stack<int> &stk)


{
vis[u] = true;
for (auto v:adj[u])
if (!vis[v])
topologicalSortUtil(v, vis, stk);

stk.push(u);
}

void topologicalSort()
{
stack<int> stk;
vector<bool> vis(V,false);

for (int i = 0; i < V; i++)


if (!vis[i])
topologicalSortUtil(i, vis, stk);

while (!stk.empty()) {
cout <<(char) ('a'+stk.top()) << " ";
stk.pop();
}
}

int min(int x, int y)


{
return (x < y)? x : y;
}

void printOrder(string words[], int n, int alpha)


{
V=alpha;
for (int i = 0; i < n-1; i++)
{
string word1 = words[i], word2 = words[i+1];
for (int j = 0; j < min(word1.length(), word2.length()); j++)
{
if (word1[j] != word2[j])
{
addEdge(word1[j]-'a', word2[j]-'a');
break;
}
}
}
topologicalSort();
}

int main()
{
string words[] = {"baa", "abcd", "abca", "cab", "cad"};
//string words[] = {"caa", "aaa", "aab"};
printOrder(words, 5, 4);
return 0;
}
 Rat in a Maze
#include <bits/stdc++.h>
using namespace std;
#define N 4

bool check(int x,int y,int maze[N][N]){


if(x>=0 && x<N && y>=0 && y<N && maze[x][y]==1) return true;
return false;
}
bool solveutil(int x,int y,int maze[N][N],int sol[N][N]){
if(x==N-1 && y==N-1) {
sol[x][y]=1;
return true;
}
if(check(x,y,maze)){
if(sol[x][y]==1) return false;
sol[x][y]=1;
if(solveutil(x+1,y,maze,sol)) return true;
if(solveutil(x,y+1,maze,sol)) return true;
sol[x][y]=0;
}
return false;
}
void solveMaze(int maze[N][N]){
int sol[N][N];
memset(sol,0,N*N*sizeof(int));
if(maze[0][0]==0 || maze[N-1][N-1]==0);
else solveutil(0,0,maze,sol);
for(int i=0;i<N;i++){
for(int j=0;j<N;j++)
cout<<sol[i][j]<<" ";
cout<<"\n";
}

}
int main()
{
int maze[N][N] = { { 1, 0, 0, 0 },
{ 1, 1, 0, 1 },
{ 0, 1, 0, 0 },
{ 1, 1, 1, 1 } };
solveMaze(maze);
return 0;
}
 Count number of ways to reach destination in a Maze (Recursion)
#include<bits/stdc++.h>
using namespace std;
#define R 4
#define C 4
int cnt=0;
bool issafe(int x,int y,int maze[R][C]){
if(x>=0 && x<R && y>=0 && y<C && maze[x][y]==1) return true;
return false;
}
void mazeutil(int x,int y,int maze[R][C]){
if(x==R-1 && y==C-1) {
cnt++;
return ;
}
if(issafe(x,y,maze)){
mazeutil(x+1,y,maze);
mazeutil(x,y+1,maze);
}
return;
}

int countPaths(int maze[R][C]){


mazeutil(0,0,maze);
return cnt;
}
int main()
{
int maze[R][C] = {{0, 0, 0, 0},
{0, -1, 0, 0},
{-1, 0, 0, 0},
{0, 0, 0, 0}};
cout << countPaths(maze);
return 0;
}
 Count number of ways to reach destination in a Maze (DP)

#include<bits/stdc++.h>
using namespace std;
#define R 4
#define C 4

int countPaths(int maze[][C])


{
if (maze[0][0]==-1)
return 0;

for (int i=0; i<R; i++)


{
if (maze[i][0] == 0)
maze[i][0] = 1;
else break;
}

for (int i=1; i<C; i++)


{
if (maze[0][i] == 0)
maze[0][i] = 1;
else break;
}

for (int i=1; i<R; i++)


{
for (int j=1; j<C; j++)
{
if (maze[i][j] == -1)
continue;
if (maze[i-1][j] > 0)
maze[i][j] = (maze[i][j] + maze[i-1][j]);
if (maze[i][j-1] > 0)
maze[i][j] = (maze[i][j] + maze[i][j-1]);
}
}
return (maze[R-1][C-1] > 0)? maze[R-1][C-1] : 0;
}

int main()
{
int maze[R][C] = {{0, 0, 0, 0},
{0, -1, 0, 0},
{-1, 0, 0, 0},
{0, 0, 0, 0}};
cout << countPaths(maze);
return 0;
}
 N-queen
#include <bits/stdc++.h>
#define N 4
using namespace std;

void printSolution(int board[N][N])


{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
cout << " " << board[i][j] << " ";
printf("\n");
}
}

bool isSafe(int board[N][N], int row, int col)


{
for(int i=0;i<col;i++)
if(board[row][i]) return false;
for(int i=row,j=col;i>=0 && j>=0;i--,j--)
if(board[i][j]) return false;
for(int i=row,j=col;i<N && j>=0;i++,j--)
if(board[i][j]) return false;

return true;
}

bool solveNQUtil(int board[N][N], int col)


{
if(col>=N) return true;
for(int i=0;i<N;i++){
if(isSafe(board,i,col))
{
board[i][col]=1;
if(solveNQUtil(board,col+1)) return true;
board[i][col]=0;
}
}
return false;
}

bool solveNQ()
{
int board[N][N] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };
if (solveNQUtil(board, 0) == false) {
cout << "Solution does not exist";
return false;
}
printSolution(board);
return true;
}

int main()
{
solveNQ();
return 0;
}
 Kruskal Algo
#include <bits/stdc++.h>
using namespace std;
const int MAX=1e4+5;
typedef long long ll;
int j=0;
int id[MAX], nodes, edges=0;
pair <ll, pair<int, int> > p[MAX];

void initialize(){
for(int i=0;i<1e4+5;i++)
id[i]=i;
}
void addEdge(int x,int y,ll weight){
p[j++]={weight,{x,y}};
edges++;
}
int root(int x){
while(id[x]!=x){
id[x]=id[id[x]];
x=id[x];
}
return x;
}
void union1(int x,int y){
id[y]=x;
}
int kruskal(){
int x,y;
ll weight=0,mincost=0;

for(int i=0;i<edges;i++){
weight=p[i].first;
x=p[i].second.first;
y=p[i].second.second;
int parentx=root(x);
int parenty=root(y);
if(parentx!=parenty){
mincost+=weight;
union1(parentx,parenty);
}
}
return mincost;
}
int main()
{
initialize();
ll minimumCost;
nodes=4;
addEdge(0, 1, 10);
addEdge(1, 3, 15);
addEdge(2, 3, 4);
addEdge(2, 0, 6);
addEdge(0, 3, 5);
sort(p, p + edges);
minimumCost = kruskal();
cout << minimumCost << endl;
return 0;
}
 Prism Algo
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pa;
map<int,list<pa> > adj;
int nodes,edge=0;
void addEdge(int u,int v,int weight){
adj[u].push_back({v,weight});
adj[v].push_back({u,weight});
edge++;
}
int prism(){
int mincost=0,weight,u;
priority_queue<pa,vector<pa>,greater<pa> > minh;
minh.push({0,0});
vector<int> spt(nodes,0);
while(!minh.empty()){
pa temp=minh.top();
minh.pop();
weight=temp.first;
u=temp.second;
//check for cycles
if(spt[u]) continue;
mincost+=weight;
spt[u]=true;
for(auto v:adj[u]){
cout<<v.first<<"-"<<v.second<<endl;
if(!spt[v.first]) minh.push({v.second,v.first});
}
}
return mincost;
}
int main()
{
int minimumCost;
nodes=4;
addEdge(0, 1, 10);
addEdge(1, 3, 15);
addEdge(2, 3, 4);
addEdge(2, 0, 6);
addEdge(0, 3, 5);
minimumCost = prism();
cout << minimumCost << endl;
return 0;
}
 Bellmann Ford (For negative edge using Adjacency list)
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pa;

int nodes,edges=0;
map<int,list<pa> > adj;

void addEdge(int u,int v,int weight){


adj[u].push_back({v,weight});
edges++;
}

void printArr(vector<int> &dist)


{
cout<<"Vertex Distance from Source\n";
for (int i = 0; i < nodes; ++i)
printf("%d \t\t %d\n", i, dist[i]);
}

// finds shortest distances from src to all other vertices using Bellman-Ford algorithm.
// The function also detects negative weight cycle
void bellmanFord(int src)
{
vector<int> dist(nodes,INT_MAX);
dist[src] = 0;

// Step 2: Relax all edges |V| - 1 times. A simple


// shortest path from src to any other vertex can have
// at-most |V| - 1 edges
for (int i = 1; i < nodes; i++) {
for (auto it:adj)
{
int u = it.first;
for(auto l:it.second)
{
int v = l.first;
int weight = l.second;
if (dist[u] != INT_MAX && dist[u] + weight < dist[v])
dist[v] = dist[u] + weight;
}
}
}

// Step 3: check for negative-weight cycles. The above


// step guarantees shortest distances if graph doesn't
// contain negative weight cycle. If we get a shorter
// path, then there is a cycle.
for (auto it : adj) {
int u = it.first;
for(auto l:it.second)
{
int v = l.first;
int weight = l.second;
if (dist[u] != INT_MAX && dist[u] + weight < dist[v])
{
cout<<"Graph contains negative weight cycle";
return; // If negative cycle is detected, simply return
}
}
}
printArr(dist);
return;
}

int main()
{
nodes = 5;
addEdge(0,1,-1);
addEdge(0,2,4);
addEdge(1,2,3);
addEdge(1,3,2);
addEdge(1,4,2);
addEdge(3,2,5);
addEdge(3,1,1);
addEdge(4,3,-3);

bellmanFord(0);
return 0;
}
 BellmanFord using graph and print the path also
#include <bits/stdc++.h>
using namespace std;
// Data structure to store a graph edge
struct Edge {
int source, dest, weight;
};

// Recursive function to print the path of a given vertex from source vertex
void printPath(vector<int> const &parent, int vertex, int source)
{
if (vertex < 0) {
return;
}

printPath(parent, parent[vertex], source);


if (vertex != source) {
cout << ", ";
}
cout << vertex;
}

// Function to run the Bellman–Ford algorithm from a given source


void bellmanFord(vector<Edge> const &edges, int source, int n)
{
// distance[] and parent[] stores the shortest path (least cost/path)
// information. Initially, all vertices except the source vertex
// weight INFINITY and no parent
vector<int> distance (n, INT_MAX);
distance[source] = 0;

vector<int> parent (n, -1);

int u, v, w, k = n;

// relaxation step (run V-1 times)


while (--k)
{
for (Edge edge: edges)
{
// edge from `u` to `v` having weight `w`
u = edge.source;
v = edge.dest;
w = edge.weight;

// if the distance to destination `v` can be


// shortened by taking edge (u, v)
if (distance[u] != INT_MAX && distance[u] + w < distance[v])
{
// update distance to the new lower value
distance[v] = distance[u] + w;

// set v's parent as `u`


parent[v] = u;
}
}
}

// run relaxation step once more for n'th time to check for negative-weight cycles
for (Edge edge: edges)
{
// edge from `u` to `v` having weight `w`
u = edge.source;
v = edge.dest;
w = edge.weight;

// if the distance to destination `u` can be shortened by taking edge (u, v)


if (distance[u] != INT_MAX && distance[u] + w < distance[v])
{
cout << "Negative-weight cycle is found!!";
return;
}
}

for (int i = 0; i < n; i++)


{
if (i != source && distance[i] < INT_MAX)
{
cout << "The distance of vertex " << i << " from the source is "
<< setw(2) << distance[i] << ". Its path is [";
printPath(parent, i, source); cout << "]" << endl;
}
}
}
int main()
{
// vector of graph edges as per the above diagram
vector<Edge> edges =
{
// (x, y, w) —> edge from `x` to `y` having weight `w`
{0, 1, -1}, {0, 2, 4}, {1, 2, 3}, {1, 3, 2},
{1, 4, 2}, {3, 2, 5}, {3, 1, 1}, {4, 3, -3}
};

// set the maximum number of nodes in the graph


int n = 5;

// run the Bellman–Ford algorithm from every node


for (int source = 0; source < n; source++) {
bellmanFord(edges, source, n);
}

return 0;
}
 Floyd-Warshall
#include <bits/stdc++.h>
using namespace std;

#define V 4
#define INF 99999

void printSolution(int dist[][V]);

void floydWarshall(int graph[][V])


{
int dist[V][V], i, j, k;

for (i = 0; i < V; i++)


for (j = 0; j < V; j++)
dist[i][j] = graph[i][j];

for (k = 0; k < V; k++) {


for (i = 0; i < V; i++) {
for (j = 0; j < V; j++) {
if (dist[i][j] > (dist[i][k] + dist[k][j]) && (dist[k][j] != INF && dist[i][k] != INF))
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
printSolution(dist);
}

void printSolution(int dist[][V])


{
cout << "The following matrix shows the shortest "
"distances"
" between every pair of vertices \n";
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == INF)
cout << "INF"
<< " ";
else
cout << dist[i][j] << " ";
}
cout << endl;
}
}

int main()
{
int graph[V][V] = { { 0, 5, INF, 10 },
{ INF, 0, 3, INF },
{ INF, INF, 0, 1 },
{ INF, INF, INF, 0 } };

floydWarshall(graph);
return 0;
}
 Hamilton Cycle
#include <bits/stdc++.h>
using namespace std;

#define V 5

bool isSafe(int v, bool graph[V][V],vector<int> &path, int pos)


{
if(graph[path[pos-1]][v]==0) return false;
for(auto i: path) if(i==v) return false;
return true;
}

bool hamCycleUtil(bool graph[V][V],vector<int> &path, int pos)


{
if(pos==V){
if(graph[path[pos-1]][path[0]]) return true;
else return false;
}
for(int i=1;i<V;i++){
if(isSafe(i,graph,path,pos)){
path[pos]=i;
if(hamCycleUtil(graph,path,pos+1)) return true;
path[pos]=-1;
}
}

return false;
}

void printSolution(vector<int> &path)


{
cout << "Solution Exists:"
" Following is one Hamiltonian Cycle \n";
for (int i = 0; i < V; i++)
cout << path[i] << " ";

cout << path[0] << " ";


cout << endl;
}

bool hamCycle(bool graph[V][V])


{
vector<int> path(V,-1);
path[0]=0;
if(!hamCycleUtil(graph,path,1)){
cout<<"Soln don't exist";
return false;
}
printSolution(path);
return true;
}

int main()
{
bool graph1[V][V] = {{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
{0, 1, 1, 1, 0}};

hamCycle(graph1);

bool graph2[V][V] = {{0, 1, 0, 1, 0},


{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 0},
{0, 1, 1, 0, 0}};

hamCycle(graph2);
return 0;
}
 Travelling Salesman Problem
#include <bits/stdc++.h>
using namespace std;
#define V 4

int travllingSalesmanProblem(int graph[][V], int s)


{
vector<int> vertex;
for (int i = 0; i < V; i++)
if (i != s)
vertex.push_back(i);

int min_path = INT_MAX;


do {
int current_pathweight = 0;

int k = s;
for (int i = 0; i < vertex.size(); i++) {
current_pathweight += graph[k][vertex[i]];
k = vertex[i];
}
current_pathweight += graph[k][s];
min_path = min(min_path, current_pathweight);

} while (
next_permutation(vertex.begin(), vertex.end()));

return min_path;
}

int main()
{
int graph[][V] = { { 0, 10, 15, 20 },
{ 10, 0, 35, 25 },
{ 15, 35, 0, 30 },
{ 20, 25, 30, 0 } };
int s = 0;
cout << travllingSalesmanProblem(graph, s) << endl;
return 0;
}
 Graph Coloring Problem
#include <bits/stdc++.h>
using namespace std;

int V;
map<int,list<int> > adj;
void addEdge(int v, int w)
{
adj[v].push_back(w);
adj[w].push_back(v);
}

void greedyColoring()
{
vector<int> result(V,-1);
result[0] = 0;

vector<bool> available(V,true);

for (int u = 1; u < V; u++)


{
fill(available.begin(),available.end(),true);
for (auto v:adj[u]){
if (result[v] != -1) available[result[v]] = false;
}

int cr;
for (cr = 0; cr < V; cr++)
if (available[cr])
break;

result[u] = cr;
}

for (int u = 0; u < V; u++)


cout << "Vertex " << u << " ---> Color "
<< result[u] << endl;
}
int main()
{
V=5;
addEdge(0, 1);
addEdge(0, 2);
addEdge(1, 2);
addEdge(1, 3);
addEdge(2, 3);
addEdge(3, 4);
cout << "Coloring of graph 1 \n";
greedyColoring();
adj.clear();

V=5;
addEdge(0, 1);
addEdge(0, 2);
addEdge(1, 2);
addEdge(1, 4);
addEdge(2, 4);
addEdge(4, 3);
cout << "\nColoring of graph 2 \n";
greedyColoring();

return 0;
}
 Snake and Ladder Problem
#include <bits/stdc++.h>
using namespace std;

int getMinDiceThrows(int move[], int N)


{
vector<bool> vis(N,false);
queue<pair<int,int>> q;
q.push({0,0});
vis[0]=true;
int step;
while(!q.empty()){
pair<int,int> temp=q.front();
q.pop();
int v=temp.first;
step=temp.second;
if(v==N-1) break;
for(int i=v;i<=(v+6);i++)
{
if(!vis[i])
{
vis[i]=true;
if(move[i]==-1)
q.push({i,step+1});
else q.push({move[i],step+1});
}
}
}
return step;
}
int main()
{
int N = 30;
int moves[N];
for (int i = 0; i < N; i++)
moves[i] = -1;

// Ladders
moves[2] = 21;
moves[4] = 7;
moves[10] = 25;
moves[19] = 28;

// Snakes
moves[26] = 0;
moves[20] = 8;
moves[16] = 3;
moves[18] = 6;

cout << "Min Dice throws required is "


<< getMinDiceThrows(moves, N);
return 0;
}
 Kosaraju Algorithm to find strongly connected component in directed graph
#include <bits/stdc++.h>
using namespace std;

int V;
map<int,list<int> > adj;
map<int,list<int> > transp;

void addEdge(int u,int v){


adj[u].push_back(v);
}

void reversedfs(int u,vector<bool> &vis)


{
vis[u] = true;
cout << u << " ";

for(auto v:transp[u])
if(!vis[v]) reversedfs(v,vis);
}

void getTranspose()
{
for (int i = 0; i < V; i++)
{
for(auto v:adj[i])
transp[v].push_back(i);
}
}

void dfs(int u, vector<bool> &vis, stack<int> &stk)


{
vis[u] = true;
for(auto v:adj[u])
if(!vis[v]) dfs(v,vis,stk);

stk.push(u);
}

void printSCCs()
{
stack<int> stk;
vector<bool> vis(V,false);

for(int i = 0; i < V; i++)


if(!vis[i])
dfs(i, vis, stk);

getTranspose();
fill(vis.begin(),vis.end(),false);

while (!stk.empty())
{
int v = stk.top();
stk.pop();

if (!vis[v])
{
reversedfs(v, vis);
cout << endl;
}
}
}

int main()
{
V=5;
addEdge(1, 0);
addEdge(0, 2);
addEdge(2, 1);
addEdge(0, 3);
addEdge(3, 4);

cout << "Following are strongly connected components in "


"given graph \n";
printSCCs();

return 0;
}
 Tarjan’s Algorithm to find Strongly Connected Components
#include<bits/stdc++.h>
using namespace std;

int V;
map<int,list<int> > adj;

void addEdge(int u, int v)


{
adj[u].push_back(v);
}
// A recursive function that finds and prints strongly connected
// components using DFS traversal
// u --> The vertex to be visited next
// disc[] --> Stores discovery times of visited vertices
// low[] -- >> earliest visited vertex (the vertex with minimum
// discovery time) that can be reached from subtree
// rooted with current vertex
// *st -- >> To store all the connected ancestors (could be part
// of SCC)
// stackMember[] --> bit/index array for faster check whether
// a node is in stack
void SCCUtil(int u,vector<int> &disc,vector<int> &low, stack<int> &stk,vector<bool> &stkmember)
{
// A static variable is used for simplicity, we can avoid use
// of static variable by passing a pointer.
static int time = 0;

disc[u] = low[u] = ++time;


stk.push(u);
stkmember[u] = true;

for(auto v:adj[u])
{
if(disc[v] == -1)
{
SCCUtil(v,disc,low,stk,stkmember);
low[u]=min(low[u],low[v]);
}
else if(stkmember[v])
low[u]=min(low[u],disc[v]);
}

// head node found, pop the stack and print an SCC


int w = 0; // To store stack extracted vertices
if (low[u] == disc[u])
{
while (stk.top() != u)
{
w = (int) stk.top();
cout << w << " ";
stkmember[w] = false;
stk.pop();
}
w = (int) stk.top();
cout << w << "\n";
stkmember[w] = false;
stk.pop();
}
}

void SCC()
{
vector<int> disc(V,-1);
vector<int> low(V,-1);
vector<bool> stkmember(V,false);
stack<int> stk;
// Call the recursive helper function to find strongly
// connected components in DFS tree with vertex 'i'
for (int i = 0; i < V; i++)
if (disc[i] == -1)
SCCUtil(i, disc, low, stk, stkmember);
}

int main()
{
cout << "\nSCCs in first graph \n";
V=5;
addEdge(1, 0);
addEdge(0, 2);
addEdge(2, 1);
addEdge(0, 3);
addEdge(3, 4);
SCC();
adj.clear();

cout << "\nSCCs in second graph \n";


V=4;
addEdge(0, 1);
addEdge(1, 2);
addEdge(2, 3);
SCC();
adj.clear();

cout << "\nSCCs in third graph \n";


V=7;
addEdge(0, 1);
addEdge(1, 2);
addEdge(2, 0);
addEdge(1, 3);
addEdge(1, 4);
addEdge(1, 6);
addEdge(3, 5);
addEdge(4, 5);
SCC();
adj.clear();

cout << "\nSCCs in fourth graph \n";


V=11;
addEdge(0,1);addEdge(0,3);
addEdge(1,2);addEdge(1,4);
addEdge(2,0);addEdge(2,6);
addEdge(3,2);
addEdge(4,5);addEdge(4,6);
addEdge(5,6);addEdge(5,7);addEdge(5,8);addEdge(5,9);
addEdge(6,4);
addEdge(7,9);
addEdge(8,9);
addEdge(9,8);
SCC();
adj.clear();
cout << "\nSCCs in fifth graph \n";
V=5;
addEdge(0,1);
addEdge(1,2);
addEdge(2,3);
addEdge(2,4);
addEdge(3,0);
addEdge(4,2);
SCC();

return 0;
}

You might also like