Вы находитесь на странице: 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;

struct node {

node_info * pt;

node * next;

np = new node;

np - > pt = ptr;

## np - > next = NULL;

if (front == NULL) {

} else {

rear = np;

## rear - > next = NULL;

node_info * remove() {

if (front == NULL) {

} else {

p = front;

1
x = p - > pt;

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++;

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();

2
}

int main() {

v[i] = 0;

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

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

## bfs(v, am, 0);

getch();

Output
enter the values for adjacency matrix row:1

3
0

4
1

## time of visitation for node 4:6

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

#include <conio.h>

int c = 0;

struct node {

char data;

## int st_time, lv_time;

}* p = NULL, * r = NULL;

struct stack {

node * pt;

stack * next;

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) {

} else {

q = top;

6
delete(q);

c++;

p = new node;

## cin >> p - > data;

p - > st_time = c;

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

a[i] = 1;

push(p);

while (j < 7) {

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;

## cin >> b[i][j];

create(a, b, 0, 0);

getch();

Output:

8
0

9
0

node popped

10
g

node popped

node popped

node popped

node popped

node popped

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;

public:

Graph(int V) {

this - > V = V;

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

Graph getTranspose();

bool isConnected();

};

/*

*/

12
/*

*/

## list < int > ::iterator i;

visited[s] = true;

q.push_back(s);

while (!q.empty()) {

s = q.front();

q.pop_front();

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);

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;

/*

*/

int main() {

Graph g(4);

14
if (g.isConnected())

else

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

Graph g1(5);

if (g1.isConnected())

else

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

return 0;

Output
\$ g++ undirected_connected_bfs.cpp

\$ a.out

## The Graph is Connected

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

## (program exited with code: 0)

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;

public:

Graph(int V) {

this - > V = V;

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

Graph getTranspose();

bool isConnected();

};

/*

*/

/*

16
*/

## list < int > ::iterator i;

visited[s] = true;

q.push_back(s);

while (!q.empty()) {

s = q.front();

q.pop_front();

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);

## list < int > ::iterator i;

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;

/*

*/

int main() {

Graph g(4);

if (g.isConnected())

18
else

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

Graph g1(5);

if (g1.isConnected())

else

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

return 0;

Output
\$ g++ ConnectivityUsingBFSDiredctedGraph.cpp

\$ a.out

## The Graph 2 is Connected

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

## (program exited with code: 0)

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;

public:

Graph(int V) {

this - > V = V;

}~Graph() {

## void addEdge(int v, int w);

bool isConnected();

Graph getTranspose();

};

/*

*/

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

visited[v] = true;

20
list < int > ::iterator i;

if (!visited[ * i])

DFSUtil( * i, visited);

/*

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

*/

Graph Graph::getTranspose() {

Graph g(V);

return g;

/*

*/

/*

## * 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;

/*

*/

int main() {

Graph g1(5);

if (g1.isConnected())

else

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

22
Graph g2(4);

if (g2.isConnected())

else

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

return 0;

Output
\$ g++ undirected_connected_dfs.cpp

\$ a.out

## The Graph is Connected

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

## (program exited with code: 0)

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;

public:

Graph(int V) {

this - > V = V;

}~Graph() {

## void addEdge(int v, int w);

bool isConnected();

Graph getTranspose();

};

/*

*/

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

visited[v] = true;

## list < int > ::iterator i;

24

if (!visited[ * i])

DFSUtil( * i, visited);

/*

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

*/

Graph Graph::getTranspose() {

Graph g(V);

return g;

/*

*/

/*

## * 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;

/*

*/

int main() {

Graph g1(5);

if (g1.isConnected())

else

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

Graph g2(4);

26

if (g2.isConnected())

else

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

return 0;

Output
\$ g++ directed_connected_dfs.cpp

\$ a.out

## The Graph is Not Connected

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

## (program exited with code: 0)

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

#include<conio.h>

## int flag = 0, v[7];

struct node_info {

int no;

}* q = NULL, * r = NULL;

struct node {

node_info * pt;

node * next;

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) {

} else {

p = top;

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;

## back_edges(v, am, j, i);

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

continue;

continue;

else {

flag = -1;

r = pop();

return (flag);

void init() {

v[i] = 0;

pop();

## int ve = 1, min, temp, temp1;

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

## 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() {

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;

## 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

32
1

## 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>

struct node {

p[6];

a[i] = 1;

while (c < 6) {

if (a[i] == 1) {

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;

int main() {

int a[7];

a[i] = 0;

int b[7][7];

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

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

## cin >> b[i][j];

prims(a, b, 0, 0);

getch();

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

35
6

36
0

00

## 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;

}* q = NULL;

struct node {

node_info * pt;

node * next;

struct node1 {

node_info * pt1;

int c = 0;

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;

delete(p);

if (c == 0) {

c++;

} else {

## np1 - > link = m;

void remove(int x) {

delete(m);

} else {

n = m;

40
m = m - > link;

delete(m);

flag = true;

## 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;

continue;

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);

continue;

return;

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

am[src][dest] = 1;

return;

int main() {

v[i] = 0;

am[i][j] = 0;

while (c < 5) {

c++;

42
}

v[i] = 0;

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

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

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

if (flag == false) {

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

getch();

Output
Enter the source and destination

43
1

## Cycles exist in graph

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

#include <list>

class Graph {

## int V; // No. of vertices

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

public:

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

};

Graph::Graph(int V) {

this - > V = V;

// 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;

## // Mark the current node as visited and enqueue it

visited[s] = true;

queue.push_back(s);

## list < int > ::iterator i;

while (!queue.empty()) {

## // Dequeue a vertex from queue and print it

s = queue.front();

queue.pop_front();

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

// and enqueue it

if ( * i == d)

return true;

## // Else, continue to do BFS

if (!visited[ * i]) {

visited[ * i] = true;

queue.push_back( * i);

46
}

return false;

int main() {

Graph g(4);

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

13

23

## There is no path from 3 to 2

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

## (program exited with code: 0)

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

#include <cstdlib>

int p[max][max];

/*

*/

int k, i, j;

p[i][j] = k;

/*

*/

## void shortest(int i, int j) {

int k = p[i][j];

if (k > 0) {

shortest(i, k);

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

shortest(k, j);

/*

*/

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

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

shortest(i, j);

/*

*/

int main() {

int i, j;

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

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

## {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)

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

#include <list>

#define NIL - 1

class Graph {

int parent[]);

public:

## void bridge(); // prints all bridges

};

Graph::Graph(int V) {

this - > V = V;

int parent[]) {

## // variable by passing a pointer.

52
static int time = 0;

## // Mark the current node as visited

visited[u] = true;

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

if (!visited[v]) {

parent[v] = u;

## // 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() {

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

parent[i] = NIL;

visited[i] = false;

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

if (visited[i] == false)

int main() {

Graph g1(5);

54

g1.bridge();

Graph g2(4);

g2.bridge();

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

Graph g3(7);

g3.bridge();

return 0;

55
Output
\$ g++ EdgeConnectivity.cpp

\$ a.out

34

03

23

12

01

## Bridges in third graph

16

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

## (program exited with code: 0)

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

#include <list>

#define NIL - 1

class Graph {

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

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

bool ap[]);

public:

## void AP(); // prints articulation points

};

Graph::Graph(int V) {

this - > V = V;

## // 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[]) {

## // Count of children in DFS Tree

int children = 0;

## // Mark the current node as visited

visited[u] = true;

## // in DFS tree and recur for it

if (!visited[v]) {

children++;

parent[v] = u;

## // one of the ancestors of u

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

## 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

ap[u] = true;

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

else if (v != parent[u])

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

void Graph::AP() {

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

59
parent[i] = NIL;

visited[i] = false;

ap[i] = false;

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

if (visited[i] == false)

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

if (ap[i] == true)

int main() {

Graph g1(5);

g1.AP();

Graph g2(4);

60

g2.AP();

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

Graph g3(7);

g3.AP();

return 0;

61
Output
\$ g++ VertexConnectivity.cpp

\$ a.out

03

12

## Articulation points in third graph

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

## (program exited with code: 0)

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;

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) {

} else {

p = top;

delete(p);

63
}

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

q = new node_info;

q - > no = i;

push(q);

v[i] = 1;

continue;

cnt++;

q = pop();

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

am[src][dest] = 1;

am[dest][src] = 1;

return;

int main() {

v[i] = 0;

am[i][j] = 0;

64
}

while (c < 9) {

c++;

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

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

am[i][j] = 0;

am[j][i] = 0;

if (i < 6) {

} 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

0 is an articulation point

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

#include <string.h>

#include <queue>

## 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();

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

q.push(v);

parent[v] = u;

visited[v] = true;

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

int u, v;

int rGraph[6][6];

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

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

68
}

int parent[6];

int max_flow = 0;

## 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