Graph code
Graph code
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;
}
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;
}
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;
}
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;
}
int V;
map<int,list<int>> adj;
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;
}
map<int,list<int>> adj;
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;
}
#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));
}
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;
}
struct cell {
int x, y,dis;
cell() {}
cell(int x, int y, int dis)
: x(x), y(y), dis(dis)
{
}
};
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;
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;
#define row 5
#define col 5
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);
}
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();
return 0;
}
Topological Sorting
#include <bits/stdc++.h>
using namespace std;
int V;
map<int,list<int> > adj;
stk.push(u);
}
void topologicalSort()
{
stack<int> stk;
vector<bool> vis(V,false);
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;
stk.push(u);
}
void topologicalSort()
{
stack<int> stk;
vector<bool> vis(V,false);
while (!stk.empty()) {
cout <<(char) ('a'+stk.top()) << " ";
stk.pop();
}
}
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
}
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;
}
#include<bits/stdc++.h>
using namespace std;
#define R 4
#define C 4
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;
return true;
}
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;
// 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;
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;
}
int u, v, w, k = n;
// 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;
return 0;
}
Floyd-Warshall
#include <bits/stdc++.h>
using namespace std;
#define V 4
#define INF 99999
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
return false;
}
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);
hamCycle(graph2);
return 0;
}
Travelling Salesman Problem
#include <bits/stdc++.h>
using namespace std;
#define V 4
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);
int cr;
for (cr = 0; cr < V; cr++)
if (available[cr])
break;
result[u] = cr;
}
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;
// 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;
int V;
map<int,list<int> > adj;
map<int,list<int> > transp;
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);
}
}
stk.push(u);
}
void printSCCs()
{
stack<int> stk;
vector<bool> vis(V,false);
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);
return 0;
}
Tarjan’s Algorithm to find Strongly Connected Components
#include<bits/stdc++.h>
using namespace std;
int V;
map<int,list<int> > adj;
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]);
}
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();
return 0;
}