Вы находитесь на странице: 1из 69

1.

Program to Traverse a Graph using BFS


#include <iostream>

#include <conio.h>

using namespace std;

int c = 0, t = 0;

struct node_info {

int no;

int st_time;

}* q = NULL, * r = NULL, * x = NULL;

struct node {

node_info * pt;

node * next;

}* front = NULL, * rear = NULL, * p = NULL, * np = NULL;

void push(node_info * ptr) {

np = new node;

np - > pt = ptr;

np - > next = NULL;

if (front == NULL) {

front = rear = np;

rear - > next = NULL;

} else {

rear - > next = np;

rear = np;

rear - > next = NULL;

node_info * remove() {

if (front == NULL) {

cout << "empty queue\n";

} else {

p = front;

1
x = p - > pt;

front = front - > next;

delete(p);

return (x);

void bfs(int * v, int am[][7], int i) {

if (c == 0) {

q = new node_info;

q - > no = i;

q - > st_time = t++;

cout << "time of visitation for node " << q - > no << ":" << q - > st_time << "\n\n";

v[i] = 1;

push(q);

c++;

for (int j = 0; j < 7; j++) {

if (am[i][j] == 0 || (am[i][j] == 1 && v[j] == 1))

continue;

else if (am[i][j] == 1 && v[j] == 0) {

r = new node_info;

r - > no = j;

r - > st_time = t++;

cout << "time of visitation for node " << r - > no << ":" << r - > st_time << "\n\n";

v[j] = 1;

push(r);

remove();

if (c <= 6 && front != NULL)

bfs(v, am, remove() - > no);

2
}

int main() {

int v[7], am[7][7];

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

v[i] = 0;

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

cout << "enter the values for adjacency matrix row:" << i + 1 << endl;

for (int j = 0; j < 7; j++) {

cin >> am[i][j];

bfs(v, am, 0);

getch();

Output
enter the values for adjacency matrix row:1

enter the values for adjacency matrix row:2

3
0

enter the values for adjacency matrix row:3

enter the values for adjacency matrix row:4

enter the values for adjacency matrix row:5

enter the values for adjacency matrix row:6

4
1

enter the values for adjacency matrix row:7

time of visitation for node 0:0

time of visitation for node 1:1

time of visitation for node 2:2

time of visitation for node 5:3

time of visitation for node 6:4

time of visitation for node 3:5

time of visitation for node 4:6

5
2. Program to Traverse a Graph using DFS
#include <iostream>

#include <conio.h>

using namespace std;

int c = 0;

struct node {

char data;

int st_time, lv_time;

}* p = NULL, * r = NULL;

struct stack {

node * pt;

stack * next;

}* top = NULL, * q = NULL, * np = NULL;

void push(node * ptr) {

np = new stack;

np - > pt = ptr;

np - > next = NULL;

if (top == NULL) {

top = np;

} else {

np - > next = top;

top = np;

node * pop() {

if (top == NULL) {

cout << "underflow\n";

} else {

q = top;

top = top - > next;

return (q - > pt);

6
delete(q);

void create(int a[], int b[][7], int i, int j) {

c++;

p = new node;

cout << "enter data for new node\n";

cin >> p - > data;

p - > st_time = c;

cout << "start time for " << p - > data << " is " << c << endl;

a[i] = 1;

push(p);

while (j < 7) {

if ((b[i][j] == 0) || (b[i][j] == 1 && a[j] == 1)) {

j++;

} else if (b[i][j] == 1 && a[j] == 0) {

create(a, b, j, 0);

r = pop();

cout << "node popped\n";

c++;

cout << "leave time for " << r - > data << " is " << c << endl;

return;

int main() {

int a[7];

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

a[i] = 0;

int b[7][7];

7
cout << "enter values for adjacency matrix" << endl;

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

cout << "enter values for " << (i + 1) << " row" << endl;

for (int j = 0; j < 7; j++) {

cin >> b[i][j];

create(a, b, 0, 0);

getch();

Output:
enter values for adjacency matrix

enter values for 1 row

enter values for 2 row

8
0

enter values for 3 row

enter values for 4 row

enter values for 5 row

enter values for 6 row

9
0

enter values for 7 row

enter data for new node

start time for a is 1

enter data for new node

start time for b is 2

node popped

leave time for b is 3

enter data for new node

start time for c is 4

enter data for new node

start time for d is 5

enter data for new node

start time for e is 6

enter data for new node

start time for f is 7

enter data for new node

10
g

start time for g is 8

node popped

leave time for g is 9

node popped

leave time for f is 10

node popped

leave time for e is 11

node popped

leave time for d is 12

node popped

leave time for c is 13

node popped

leave time for a is 14

11
3. Program to Check the Connectivity of Undirected Graph using BFS
#include <iostream>

#include <list>

#include <queue>

using namespace std;

/*

* Class Declaration

*/

class Graph {

private:

int V;

list < int > * adj;

public:

Graph(int V) {

this - > V = V;

adj = new list < int > [V];

void addEdge(int v, int w);

void BFS(int s, bool visited[]);

Graph getTranspose();

bool isConnected();

};

/*

* Add Edge to connect v and w

*/

void Graph::addEdge(int v, int w) {

adj[v].push_back(w);

adj[w].push_back(v);

12
/*

* A recursive function to print BFS starting from s

*/

void Graph::BFS(int s, bool visited[]) {

list < int > q;

list < int > ::iterator i;

visited[s] = true;

q.push_back(s);

while (!q.empty()) {

s = q.front();

q.pop_front();

for (i = adj[s].begin(); i != adj[s].end(); ++i) {

if (!visited[ * i]) {

visited[ * i] = true;

q.push_back( * i);

/*

* Function that returns reverse (or transpose) of this graph

*/

Graph Graph::getTranspose() {

Graph g(V);

for (int v = 0; v < V; v++) {

list < int > ::iterator i;

for (i = adj[v].begin(); i != adj[v].end(); ++i) {

g.adj[ * i].push_back(v);

return g;

13
}

/*

* Check if Graph is Connected

*/

bool Graph::isConnected() {

bool visited[V];

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

visited[i] = false;

BFS(0, visited);

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

if (visited[i] == false)

return false;

Graph gr = getTranspose();

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

visited[i] = false;

gr.BFS(0, visited);

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

if (visited[i] == false)

return false;

return true;

/*

* Main Contains Menu

*/

int main() {

Graph g(4);

g.addEdge(0, 1);

g.addEdge(0, 2);

g.addEdge(1, 2);

g.addEdge(2, 3);

g.addEdge(3, 3);

14
if (g.isConnected())

cout << "The Graph is Connected" << endl;

else

cout << "The Graph is not Connected" << endl;

Graph g1(5);

g1.addEdge(0, 1);

g1.addEdge(1, 2);

g1.addEdge(2, 3);

g1.addEdge(3, 0);

g1.addEdge(2, 4);

g1.addEdge(4, 2);

if (g1.isConnected())

cout << "The Graph is Connected" << endl;

else

cout << "The Graph is not Connected" << endl;

return 0;

Output
$ g++ undirected_connected_bfs.cpp

$ a.out

The Graph is Connected

The Graph is Connected

------------------

(program exited with code: 0)

Press return to continue

15
4. Program to Check the Connectivity of directed Graph using BFS
#include <iostream>

#include <list>

#include <queue>

using namespace std;

/*

* Class Declaration

*/

class Graph {

private:

int V;

list < int > * adj;

public:

Graph(int V) {

this - > V = V;

adj = new list < int > [V];

void addEdge(int v, int w);

void BFS(int s, bool visited[]);

Graph getTranspose();

bool isConnected();

};

/*

* Add Edge to connect v and w

*/

void Graph::addEdge(int v, int w) {

adj[v].push_back(w);

//adj[w].push_back(v);

/*

* A recursive function to print BFS starting from s

16
*/

void Graph::BFS(int s, bool visited[]) {

list < int > q;

list < int > ::iterator i;

visited[s] = true;

q.push_back(s);

while (!q.empty()) {

s = q.front();

q.pop_front();

for (i = adj[s].begin(); i != adj[s].end(); ++i) {

if (!visited[ * i]) {

visited[ * i] = true;

q.push_back( * i);

/*

* Function that returns reverse (or transpose) of this graph

*/

Graph Graph::getTranspose() {

Graph g(V);

for (int v = 0; v < V; v++) {

list < int > ::iterator i;

for (i = adj[v].begin(); i != adj[v].end(); ++i) {

g.adj[ * i].push_back(v);

return g;

/*

17
* Check if Graph is Connected

*/

bool Graph::isConnected() {

bool visited[V];

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

visited[i] = false;

BFS(0, visited);

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

if (visited[i] == false)

return false;

Graph gr = getTranspose();

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

visited[i] = false;

gr.BFS(0, visited);

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

if (visited[i] == false)

return false;

return true;

/*

* Main Contains Menu

*/

int main() {

Graph g(4);

g.addEdge(0, 1);

g.addEdge(0, 2);

g.addEdge(1, 2);

g.addEdge(2, 3);

g.addEdge(3, 3);

if (g.isConnected())

cout << "The Graph 1 is Connected" << endl;

18
else

cout << "The Graph 1 is not Connected" << endl;

Graph g1(5);

g1.addEdge(0, 1);

g1.addEdge(1, 2);

g1.addEdge(2, 3);

g1.addEdge(3, 0);

g1.addEdge(2, 4);

g1.addEdge(4, 2);

if (g1.isConnected())

cout << "The Graph 2 is Connected" << endl;

else

cout << "The Graph 2 is not Connected" << endl;

return 0;

Output
$ g++ ConnectivityUsingBFSDiredctedGraph.cpp

$ a.out

The Graph 1 is not Connected

The Graph 2 is Connected

------------------

(program exited with code: 0)

Press return to continue

19
5. Program to Check the connectivity of Undirected Graph using DFS

#include <iostream>

#include <list>

#include <stack>

using namespace std;

/*

* Class Declaration

*/

class Graph {

private:

int V;

list < int > * adj;

void DFSUtil(int v, bool visited[]);

public:

Graph(int V) {

this - > V = V;

adj = new list < int > [V];

}~Graph() {

delete[] adj;

void addEdge(int v, int w);

bool isConnected();

Graph getTranspose();

};

/*

* A recursive function to print DFS starting from v

*/

void Graph::DFSUtil(int v, bool visited[]) {

visited[v] = true;

20
list < int > ::iterator i;

for (i = adj[v].begin(); i != adj[v].end(); ++i)

if (!visited[ * i])

DFSUtil( * i, visited);

/*

* Function that returns reverse (or transpose) of this graph

*/

Graph Graph::getTranspose() {

Graph g(V);

for (int v = 0; v < V; v++) {

list < int > ::iterator i;

for (i = adj[v].begin(); i != adj[v].end(); ++i) {

g.adj[ * i].push_back(v);

return g;

/*

* Add Edge to connect v and w

*/

void Graph::addEdge(int v, int w) {

adj[v].push_back(w);

adj[w].push_back(v);

/*

* Check if Graph is Connected

*/

bool Graph::isConnected() {

21
bool visited[V];

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

visited[i] = false;

DFSUtil(0, visited);

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

if (visited[i] == false)

return false;

Graph gr = getTranspose();

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

visited[i] = false;

gr.DFSUtil(0, visited);

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

if (visited[i] == false)

return false;

return true;

/*

* Main Contains Menu

*/

int main() {

Graph g1(5);

g1.addEdge(0, 1);

g1.addEdge(1, 2);

g1.addEdge(2, 3);

g1.addEdge(3, 0);

g1.addEdge(2, 4);

g1.addEdge(4, 2);

if (g1.isConnected())

cout << "The Graph is Conneted" << endl;

else

cout << "The Graph is not Connected" << endl;

22
Graph g2(4);

g2.addEdge(0, 1);

g2.addEdge(1, 2);

g2.addEdge(2, 3);

if (g2.isConnected())

cout << "The Graph is Connected" << endl;

else

cout << "The Graph is not Connected" << endl;

return 0;

Output
$ g++ undirected_connected_dfs.cpp

$ a.out

The Graph is Connected

The Graph is Connected

------------------

(program exited with code: 0)

Press return to continue

23
6. Program to Check the connectivity of Directed Graph using DFS
#include <iostream>

#include <list>

#include <stack>

using namespace std;

/*

* Class Declaration

*/

class Graph {

private:

int V;

list < int > * adj;

void DFSUtil(int v, bool visited[]);

public:

Graph(int V) {

this - > V = V;

adj = new list < int > [V];

}~Graph() {

delete[] adj;

void addEdge(int v, int w);

bool isConnected();

Graph getTranspose();

};

/*

* A recursive function to print DFS starting from v

*/

void Graph::DFSUtil(int v, bool visited[]) {

visited[v] = true;

list < int > ::iterator i;

24
for (i = adj[v].begin(); i != adj[v].end(); ++i)

if (!visited[ * i])

DFSUtil( * i, visited);

/*

* Function that returns reverse (or transpose) of this graph

*/

Graph Graph::getTranspose() {

Graph g(V);

for (int v = 0; v < V; v++) {

list < int > ::iterator i;

for (i = adj[v].begin(); i != adj[v].end(); ++i) {

g.adj[ * i].push_back(v);

return g;

/*

* Add Edge to connect v and w

*/

void Graph::addEdge(int v, int w) {

adj[v].push_back(w);

/*

* Check if Graph is Connected

*/

bool Graph::isConnected() {

bool visited[V];

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

visited[i] = false;

DFSUtil(0, visited);

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

if (visited[i] == false)

return false;

Graph gr = getTranspose();

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

visited[i] = false;

gr.DFSUtil(0, visited);

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

if (visited[i] == false)

return false;

return true;

/*

* Main Contains Menu

*/

int main() {

Graph g1(5);

g1.addEdge(0, 1);

g1.addEdge(1, 2);

g1.addEdge(2, 3);

g1.addEdge(3, 0);

g1.addEdge(2, 4);

g1.addEdge(4, 2);

if (g1.isConnected())

cout << "The Graph is Conneted" << endl;

else

cout << "The Graph is not Connected" << endl;

Graph g2(4);

g2.addEdge(0, 1);

g2.addEdge(1, 2);

26
g2.addEdge(2, 3);

if (g2.isConnected())

cout << "The Graph is Connected" << endl;

else

cout << "The Graph is not Connected" << endl;

return 0;

Output
$ g++ directed_connected_dfs.cpp

$ a.out

The Graph is Connected

The Graph is Not Connected

------------------

(program exited with code: 0)

Press return to continue

27
7. Program to Find MST(Minimum Spanning Tree) using Kruskal's
Algorithm
#include<iostream>

#include<conio.h>

using namespace std;

int flag = 0, v[7];

struct node_info {

int no;

}* q = NULL, * r = NULL;

struct node {

node_info * pt;

node * next;

}* top = NULL, * p = NULL, * np = NULL;

void push(node_info * ptr) {

np = new node;

np - > pt = ptr;

np - > next = NULL;

if (top == NULL) {

top = np;

} else {

np - > next = top;

top = np;

node_info * pop() {

if (top == NULL) {

cout << "underflow\n";

} else {

p = top;

top = top - > next;

return (p - > pt);

28
delete(p);

int back_edges(int * v, int am[][7], int i, int k) {

q = new node_info;

q - > no = i;

push(q);

v[i] = 1;

for (int j = 0; j < 7; j++) {

if (am[i][j] == 1 && v[j] == 0) {

back_edges(v, am, j, i);

} else if (am[i][j] == 0)

continue;

else if ((j == k) && (am[i][k] == 1 && v[j] == 1))

continue;

else {

flag = -1;

r = pop();

return (flag);

void init() {

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

v[i] = 0;

while (top != NULL) {

pop();

void kruskals(int am[][7], int wm[][7]) {

int ve = 1, min, temp, temp1;

29
cout << "/n/nEDGES CREATED AS FOLLOWS:-/n/n";

while (ve <= 6) {

min = 999, temp = 0, temp1 = 0;

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

for (int j = 0; j < 7; j++) {

if ((wm[i][j] < min) && wm[i][j] != 0) {

min = wm[i][j];

temp = i;

temp1 = j;

} else if (wm[i][j] == 0)

continue;

wm[temp][temp1] = wm[temp1][temp] = 999;

am[temp][temp1] = am[temp1][temp] = 1;

init();

if (back_edges(v, am, temp, 0) < 0) {

am[temp][temp1] = am[temp1][temp] = 0;

flag = 0;

continue;

} else {

cout << "edge created between " << temp << " th node and " << temp1 << " th node" << endl;

ve++;

int main() {

int am[7][7], wm[7][7];

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

v[i] = 0;

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

30
for (int j = 0; j < 7; j++) {

am[i][j] = 0;

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

cout << "enter the values for weight matrix row:" << i + 1 << endl;

for (int j = 0; j < 7; j++) {

cin >> wm[i][j];

kruskals(am, wm);

getch();

Output
enter the values for weight matrix row:1

enter the values for weight matrix row:2

31
enter the values for weight matrix row:3

enter the values for weight matrix row:4

enter the values for weight matrix row:5

enter the values for weight matrix row:6

32
1

enter the values for weight matrix row:7

EDGES CREATED AS FOLLOWS:-edge created between 2 th node and 3 th node

edge created between 4 th node and 6 th node

edge created between 5 th node and 6 th node

edge created between 1 th node and 2 th node

edge created between 2 th node and 5 th node

edge created between 0 th node and 1 th node

33
8. Program to find MST(Minimum Spanning Tree) using Prim's Algorithm
#include <iostream>

#include <conio.h>

using namespace std;

struct node {

int fr, to, cost;

p[6];

int c = 0, temp1 = 0, temp = 0;

void prims(int * a, int b[][7], int i, int j) {

a[i] = 1;

while (c < 6) {

int min = 999;

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

if (a[i] == 1) {

for (int j = 0; j < 7;) {

if (b[i][j] >= min || b[i][j] == 0) {

j++;

} else if (b[i][j] < min) {

min = b[i][j];

temp = i;

temp1 = j;

a[temp1] = 1;

p[c].fr = temp;

p[c].to = temp1;

p[c].cost = min;

c++;

34
b[temp][temp1] = b[temp1][temp] = 1000;

for (int k = 0; k < 6; k++) {

cout << "source node:" << p[k].fr << endl;

cout << "destination node:" << p[k].to << endl;

cout << "weight of node" << p[k].cost << endl;

int main() {

int a[7];

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

a[i] = 0;

int b[7][7];

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

cout << "enter values for " << (i + 1) << " row" << endl;

for (int j = 0; j < 7; j++) {

cin >> b[i][j];

prims(a, b, 0, 0);

getch();

Output
enter values of adjacency matrix for a 7 node graph:

enter values for 1 row

35
6

enter values for 2 row

enter values for 3 row

enter values for 4 row

enter values for 5 row

36
0

enter values for 6 row

00

enter values for 7 row

MINIMUM SPANNING TREE AND ORDER OF TRAVERSAL:

source node:0

destination node:1

weight of node3

source node:1

destination node:2

weight of node2

source node:2

37
destination node:3

weight of node1

source node:2

destination node:5

weight of node2

source node:5

destination node:6

weight of node1

source node:6

destination node:4

weight of node1

38
9. Program to Check Cycle in a Graph using Topological Sort
#include<iostream>

#include<conio.h>

using namespace std;

struct node_info {

int no;

int lv_time, st_time;

}* q = NULL;

struct node {

node_info * pt;

node * next;

}* top = NULL, * p = NULL, * np = NULL;

struct node1 {

node1 * link;

node_info * pt1;

}* head = NULL, * m = NULL, * n = NULL, * np1 = NULL;

int c = 0;

bool flag = false;

void push(node_info * ptr) {

np = new node;

np - > pt = ptr;

np - > next = NULL;

if (top == NULL) {

top = np;

} else {

np - > next = top;

top = np;

node_info * pop() {

if (top == NULL) {

39
cout << "underflow\n";

} else {

p = top;

top = top - > next;

return (p - > pt);

delete(p);

void store(node_info * ptr1) {

np1 = new node1;

np1 - > pt1 = ptr1;

np1 - > link = NULL;

if (c == 0) {

head = np1;

m = head;

m - > link = NULL;

c++;

} else {

m = head;

np1 - > link = m;

head = np1;

void remove(int x) {

m = head;

if ((m - > pt1) - > no == x) {

head = head - > link;

delete(m);

} else {

while ((m - > pt1) - > no != x && m - > link != NULL) {

n = m;

40
m = m - > link;

if ((m - > pt1) - > no == x) {

n - > link = m - > link;

delete(m);

} else if (m - > link == NULL) {

flag = true;

cout << "Cycles do not exist in graph\n";

void topo(int * v, int am[][5], int i) {

q = new node_info;

q - > no = i;

q - > st_time = c;

push(q);

v[i] = 1;

for (int j = 0; j < 5; j++) {

if (am[i][j] == 0 || (am[i][j] == 1 && v[j] == 1))

continue;

else if (am[i][j] == 1 && v[j] == 0) {

c++;

topo(v, am, j);

c++;

q = pop();

q - > lv_time = c;

store(q);

return;

41
void topo1(int * v, int am[][5], int i) {

v[i] = 1;

remove(i);

for (int j = 0; j < 5; j++) {

if (am[i][j] == 0 || (am[i][j] == 1 && v[j] == 1)) {

continue;

} else if (am[i][j] == 1 && v[j] == 0) {

topo1(v, am, j);

return;

void addEdge(int am[][5], int src, int dest) {

am[src][dest] = 1;

return;

int main() {

int v[5], am[5][5], amt[5][5], c = 0, a, b;

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

v[i] = 0;

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

for (int j = 0; j < 5; j++) {

am[i][j] = 0;

while (c < 5) {

cout << "Enter the source and destination\n";

cin >> a >> b;

addEdge(am, a, b);

c++;

42
}

topo(v, am, 0);

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

v[i] = 0;

for (int j = 0; j < 5; j++) {

amt[j][i] = am[i][j];

if (head != NULL) {

topo1(v, amt, (head - > pt1) - > no);

if (flag == false) {

cout << "Cycles exist in graph\n";

getch();

Output
Enter the source and destination

Enter the source and destination

Enter the source and destination

Enter the source and destination

43
1

Enter the source and destination

Cycles exist in graph

44
10. Program to Find the Shortest Path Between Two Vertices Using
Dijkstra’s Algorithm
#include <iostream>

#include <list>

using namespace std;

// This class represents a directed graph using adjacency list representation

class Graph {

int V; // No. of vertices

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

public:

Graph(int V); // Constructor

void addEdge(int v, int w); // function to add an edge to graph

bool isReachable(int s, int d); // returns true if there is a path from s to d

};

Graph::Graph(int V) {

this - > V = V;

adj = new list < int > [V];

void Graph::addEdge(int v, int w) {

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

// A BFS based function to check whether d is reachable from s.

bool Graph::isReachable(int s, int d) {

// Base case

if (s == d)

return true;

// Mark all the vertices as not visited

45
bool * visited = new bool[V];

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

visited[i] = false;

// Create a queue for BFS

list < int > queue;

// Mark the current node as visited and enqueue it

visited[s] = true;

queue.push_back(s);

// it will be used to get all adjacent vertices of a vertex

list < int > ::iterator i;

while (!queue.empty()) {

// Dequeue a vertex from queue and print it

s = queue.front();

queue.pop_front();

// Get all adjacent vertices of the dequeued vertex s

// If a adjacent has not been visited, then mark it visited

// and enqueue it

for (i = adj[s].begin(); i != adj[s].end(); ++i) {

// If this adjacent node is the destination node, then return true

if ( * i == d)

return true;

// Else, continue to do BFS

if (!visited[ * i]) {

visited[ * i] = true;

queue.push_back( * i);

46
}

return false;

// Driver program to test methods of graph class

int main() {

Graph g(4);

g.addEdge(0, 1);

g.addEdge(0, 2);

g.addEdge(1, 2);

g.addEdge(2, 0);

g.addEdge(2, 3);

g.addEdge(3, 3);

cout << "Enter the source and destination vertices: (0-3)";

int u, v;

cin >> u >> v;

if (g.isReachable(u, v))

cout << "\nThere is a path from " << u << " to " << v;

else

cout << "\nThere is no path from " << u << " to " << v;

int temp;

temp = u;

u = v;

v = temp;

if (g.isReachable(u, v))

cout << "\nThere is a path from " << u << " to " << v;

else

cout << "\nThere is no path from " << u << " to " << v;

return 0;

47
Output
$ g++ PathBetweenNodes.cpp

$ a.out

Enter the source and destination vertices: (0-3)

13

There is a path from 1 to 3

There is no path from 3 to 1

Enter the source and destination vertices: (0-3)

23

There is a path from 2 to 3

There is no path from 3 to 2

------------------

(program exited with code: 0)

Press return to continue

48
11. Program to Find All Pairs Shortest Path using Floyd- warshall’s
Algorithm
#include <iostream>

#include <cstdlib>

#define max 10# define infi 999

using namespace std;

int p[max][max];

/*

* All Pairs Shortest Path using Floyd's Algorithm

*/

void allpairshort(int a[max][max], int n) {

int k, i, j;

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

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

for (j = 0; j < n; j++) {

if (a[i][k] + a[k][j] < a[i][j]) {

a[i][j] = a[i][k] + a[k][j];

p[i][j] = k;

/*

* Storing the shortest path

*/

void shortest(int i, int j) {

int k = p[i][j];

if (k > 0) {

shortest(i, k);

49
cout << " " << k << " ";

shortest(k, j);

/*

* Display the Shortest Path

*/

void findpath(int a[max][max], int i, int j, int n) {

cout << "Path from " << i << " to " << j << ":";

if (a[i][j] < infi) {

cout << " " << i << " ";

shortest(i, j);

cout << " " << j << " ";

/*

* Main Contains Menu

*/

int main() {

int i, j;

int a[][10] = {{0, 10, infi, 30, 100},


{infi, 0 , 50, infi, infi},

{infi, infi , 0, infi, 10},

{infi, infi , 20, 0, 60},

{infi, infi , infi, infi, 0},

};

allpairshort(a, 5);

findpath(a, 0, 4, 5);

return 0;

50
Output
$ g++ allpairshortestpath.cpp

$ a.out

Path from 0 to 4: 0 3 2 4

------------------

(program exited with code: 1)

Press return to continue

51
12. Program to find edge connectivity of a graph
#include<iostream>

#include <list>

#define NIL - 1

using namespace std;

// A class that represents an undirected graph

class Graph {

int V; // No. of vertices

list < int > * adj; // A dynamic array of adjacency lists

void bridgeUtil(int v, bool visited[], int disc[], int low[],

int parent[]);

public:

Graph(int V); // Constructor

void addEdge(int v, int w); // function to add an edge to graph

void bridge(); // prints all bridges

};

Graph::Graph(int V) {

this - > V = V;

adj = new list < int > [V];

void Graph::addEdge(int v, int w) {

adj[v].push_back(w);

adj[w].push_back(v); // Note: the graph is undirected

void Graph::bridgeUtil(int u, bool visited[], int disc[], int low[],

int parent[]) {

// A static variable is used for simplicity, we can avoid use of static

// variable by passing a pointer.

52
static int time = 0;

// Mark the current node as visited

visited[u] = true;

// Initialize discovery time and low value

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

// Go through all vertices aadjacent to this

list < int > ::iterator i;

for (i = adj[u].begin(); i != adj[u].end(); ++i) {

int v = * i; // v is current adjacent of u

// If v is not visited yet, then recur for it

if (!visited[v]) {

parent[v] = u;

bridgeUtil(v, visited, disc, low, parent);

// Check if the subtree rooted with v has a connection to

// one of the ancestors of u

low[u] = min(low[u], low[v]);

// If the lowest vertex reachable from subtree under v is

// below u in DFS tree, then u-v is a bridge

if (low[v] > disc[u])

cout << u << " " << v << endl;

// Update low value of u for parent function calls.

else if (v != parent[u])

low[u] = min(low[u], disc[v]);

53
}

// DFS based function to find all bridges. It uses recursive function bridgeUtil()

void Graph::bridge() {

// Mark all the vertices as not visited

bool * visited = new bool[V];

int * disc = new int[V];

int * low = new int[V];

int * parent = new int[V];

// Initialize parent and visited arrays

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

parent[i] = NIL;

visited[i] = false;

// Call the recursive helper function to find Bridges

// in DFS tree rooted with vertex 'i'

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

if (visited[i] == false)

bridgeUtil(i, visited, disc, low, parent);

// Driver program to test above function

int main() {

// Create graphs given in above diagrams

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

Graph g1(5);

g1.addEdge(1, 0);

g1.addEdge(0, 2);

54
g1.addEdge(2, 1);

g1.addEdge(0, 3);

g1.addEdge(3, 4);

g1.bridge();

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

Graph g2(4);

g2.addEdge(0, 1);

g2.addEdge(1, 2);

g2.addEdge(2, 3);

g2.bridge();

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

Graph g3(7);

g3.addEdge(0, 1);

g3.addEdge(1, 2);

g3.addEdge(2, 0);

g3.addEdge(1, 3);

g3.addEdge(1, 4);

g3.addEdge(1, 6);

g3.addEdge(3, 5);

g3.addEdge(4, 5);

g3.bridge();

return 0;

55
Output
$ g++ EdgeConnectivity.cpp

$ a.out

Bridges in first graph

34

03

Bridges in second graph

23

12

01

Bridges in third graph

16

------------------

(program exited with code: 0)

Press return to continue

56
13. Program to find vertex connectivity of a graph
#include<iostream>

#include <list>

#define NIL - 1

using namespace std;

// A class that represents an undirected graph

class Graph {

int V; // No. of vertices

list < int > * adj; // A dynamic array of adjacency lists

void APUtil(int v, bool visited[], int disc[], int low[], int parent[],

bool ap[]);

public:

Graph(int V); // Constructor

void addEdge(int v, int w); // function to add an edge to graph

void AP(); // prints articulation points

};

Graph::Graph(int V) {

this - > V = V;

adj = new list < int > [V];

void Graph::addEdge(int v, int w) {

adj[v].push_back(w);

adj[w].push_back(v); // Note: the graph is undirected

// A recursive function that find articulation points using DFS traversal

// u --> The vertex to be visited next

// visited[] --> keeps tract of visited vertices

// disc[] --> Stores discovery times of visited vertices

57
// parent[] --> Stores parent vertices in DFS tree

// ap[] --> Store articulation points

void Graph::APUtil(int u, bool visited[], int disc[], int low[], int parent[],

bool ap[]) {

// A static variable is used for simplicity, we can avoid use of static

// variable by passing a pointer.

static int time = 0;

// Count of children in DFS Tree

int children = 0;

// Mark the current node as visited

visited[u] = true;

// Initialize discovery time and low value

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

// Go through all vertices aadjacent to this

list < int > ::iterator i;

for (i = adj[u].begin(); i != adj[u].end(); ++i) {

int v = * i; // v is current adjacent of u

// If v is not visited yet, then make it a child of u

// in DFS tree and recur for it

if (!visited[v]) {

children++;

parent[v] = u;

APUtil(v, visited, disc, low, parent, ap);

// Check if the subtree rooted with v has a connection to

// one of the ancestors of u

58
low[u] = min(low[u], low[v]);

// u is an articulation point in following cases

// (1) u is root of DFS tree and has two or more chilren.

if (parent[u] == NIL && children > 1)

ap[u] = true;

// (2) If u is not root and low value of one of its child is more

// than discovery value of u.

if (parent[u] != NIL && low[v] >= disc[u])

ap[u] = true;

// Update low value of u for parent function calls.

else if (v != parent[u])

low[u] = min(low[u], disc[v]);

// The function to do DFS traversal. It uses recursive function APUtil()

void Graph::AP() {

// Mark all the vertices as not visited

bool * visited = new bool[V];

int * disc = new int[V];

int * low = new int[V];

int * parent = new int[V];

bool * ap = new bool[V]; // To store articulation points

// Initialize parent and visited, and ap(articulation point) arrays

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

59
parent[i] = NIL;

visited[i] = false;

ap[i] = false;

// Call the recursive helper function to find articulation points

// in DFS tree rooted with vertex 'i'

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

if (visited[i] == false)

APUtil(i, visited, disc, low, parent, ap);

// Now ap[] contains articulation points, print them

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

if (ap[i] == true)

cout << i << " ";

// Driver program to test above function

int main() {

// Create graphs given in above diagrams

cout << "\nArticulation points in first graph \n";

Graph g1(5);

g1.addEdge(1, 0);

g1.addEdge(0, 2);

g1.addEdge(2, 1);

g1.addEdge(0, 3);

g1.addEdge(3, 4);

g1.AP();

cout << "\nArticulation points in second graph \n";

Graph g2(4);

60
g2.addEdge(0, 1);

g2.addEdge(1, 2);

g2.addEdge(2, 3);

g2.AP();

cout << "\nArticulation points in third graph \n";

Graph g3(7);

g3.addEdge(0, 1);

g3.addEdge(1, 2);

g3.addEdge(2, 0);

g3.addEdge(1, 3);

g3.addEdge(1, 4);

g3.addEdge(1, 6);

g3.addEdge(3, 5);

g3.addEdge(4, 5);

g3.AP();

return 0;

61
Output
$ g++ VertexConnectivity.cpp

$ a.out

Articulation points in first graph

03

Articulation points in second graph

12

Articulation points in third graph

------------------

(program exited with code: 0)

Press return to continue

62
14. Program to Find Number of Articulation points in a Graph
#include<iostream>

#include<conio.h>

using namespace std;

int cnt = 0;

struct node_info {

int no;

}* q = NULL, * r = NULL;

struct node {

node_info * pt;

node * next;

}* top = NULL, * p = NULL, * np = NULL;

void push(node_info * ptr) {

np = new node;

np - > pt = ptr;

np - > next = NULL;

if (top == NULL) {

top = np;

} else {

np - > next = top;

top = np;

node_info * pop() {

if (top == NULL) {

cout << "underflow\n";

} else {

p = top;

top = top - > next;

return (p - > pt);

delete(p);

63
}

int topo(int * v, int am[][7], int i) {

q = new node_info;

q - > no = i;

push(q);

v[i] = 1;

for (int j = 0; j < 7; j++) {

if (am[i][j] == 0 || (am[i][j] == 1 && v[j] == 1))

continue;

else if (am[i][j] == 1 && v[j] == 0) {

cnt++;

topo(v, am, j);

q = pop();

void addEdge(int am[][7], int src, int dest) {

am[src][dest] = 1;

am[dest][src] = 1;

return;

int main() {

int v[7], am[7][7], amt[7][7], c = 0, a, b, x = 0;

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

v[i] = 0;

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

for (int j = 0; j < 7; j++) {

am[i][j] = 0;

64
}

while (c < 9) {

cout << "Enter the source and destination\n";

cin >> a >> b;

addEdge(am, a, b);

c++;

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

for (int j = 0; j < 7; j++) {

amt[i][j] = am[i][j];

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

for (int j = 0; j < 7; j++) {

am[i][j] = 0;

am[j][i] = 0;

if (i < 6) {

topo(v, am, i + 1);

} else {

topo(v, am, 0);

if (cnt < 5) {

cout << endl << i << " is an articulation point" << endl;

cnt = 0;

for (int j = 0; j < 7; j++) {

am[i][j] = amt[i][j];

am[j][i] = amt[j][i];

v[j] = 0;

65
while (top != NULL) {

pop();

getch();

66
Output:
Enter the source and destination

Enter the source and destination

Enter the source and destination

Enter the source and destination

Enter the source and destination

Enter the source and destination

Enter the source and destination

Enter the source and destination

Enter the source and destination

0 is an articulation point

67
15. Program to Implement Ford–Fulkerson Algorithm
#include <iostream>

#include <string.h>

#include <queue>

using namespace std;

bool bfs(int rGraph[][6], int s, int t, int parent[]) {

bool visited[6];

memset(visited, 0, sizeof(visited));

queue < int > q;

q.push(s);

visited[s] = true;

parent[s] = -1;

while (!q.empty()) {

int u = q.front();

q.pop();

for (int v = 0; v < 6; v++) {

if (visited[v] == false && rGraph[u][v] > 0) {

q.push(v);

parent[v] = u;

visited[v] = true;

return (visited[t] == true);

int fordFulkerson(int graph[6][6], int s, int t) {

int u, v;

int rGraph[6][6];

for (u = 0; u < 6; u++) {

for (v = 0; v < 6; v++) {

rGraph[u][v] = graph[u][v];

68
}

int parent[6];

int max_flow = 0;

while (bfs(rGraph, s, t, parent)) {

int path_flow = INT_MAX;

for (v = t; v != s; v = parent[v]) {

u = parent[v];

path_flow = min(path_flow, rGraph[u][v]);

for (v = t; v != s; v = parent[v]) {

u = parent[v];

rGraph[u][v] -= path_flow;

rGraph[v][u] += path_flow;

max_flow += path_flow;

return max_flow;

int main() {

int graph[6][6] = { {0, 16, 13, 0, 0, 0},


{0, 0, 10, 12, 0, 0},

{0, 4, 0, 0, 14, 0},

{0, 0, 9, 0, 0, 20},

{0, 0, 0, 7, 0, 4},

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

cout << "The maximum possible flow is " << fordFulkerson(graph, 0, 5);

getch();

Output
The maximum possible flow is 23

69