Stats

Tuesday, 13 May 2014

DEPTH FIRST SEARCH (DFS) & BREADTH FIRST SEARCH (BFS) C++ CODE

#include<iostream> 
#include<conio.h>
using namespace std;

int cost[10][10], k, qu[10], front, rare, visit[10], visited[10], i, j, v, stk[10], top,m,n;
void bfs()
{
cout <<"\nEnter no of vertices: ";
cin >> n;
cout <<"Enter no of edges: ";
cin >> m;
cout <<"\nEnter Edges \n";
for (k = 1; k <= m; k++)
{
cin >> i >> j; 
cost[i][j] = 1; //ASSUME COST BETWEN EDGES i & j IS 1
}
cout <<"Enter Initial Vertex: ";
cin >> v;
cout <<"Visited Vertices\n";
cout << v;
visited[v] = 1;
k = 1;
while (k < n)
{
for (j = 1; j <= n; j++)
if (cost[v][j] != 0 && visited[j] != 1 && visit[j] != 1)
{
visit[j] = 1; qu[rare++] = j;
}
v = qu[front++];
cout << v << " ";
k++;
visit[v] = 0;
visited[v] = 1;
}
}
void dfs()
{
cout << "Enter no of vertices: ";
cin >> n;
cout << "Enter no of edges: ";
cin >> m;
cout << "\nEnter Edges \n";
for (k = 1; k <= m; k++)
{
cin >> i >> j;
cost[i][j] = 1;
}
cout <<"Enter Initial Vertex: ";
cin >> v;
cout <<"Visited Vertices\n";
cout << v << " ";
visited[v] = 1;
k = 1;
while (k < n)
{
for (j = n; j >= 1; j--)
if (cost[v][j] != 0 && visited[j] != 1 && visit[j] != 1)
{
visit[j] = 1;
stk[top] = j;
top++;
}
v = stk[--top];
cout << v << " ";
k++; visit[v] = 0;
visited[v] = 1;
}
}

void main()
{
int choice;
cout <<"1.DFS\n2.BFS";
cout <<"\nSelect Method: ";
cin >> choice;
if (choice == 1)
dfs();
else
bfs();
getch();
}

OUTPUT

1.DFS
2.BFS
Select Method: 1
Enter no of vertices: 6
Enter no of edges: 6

Enter Edges
1
2
1
3
1
4
2
5
2
6
3
6
Enter Initial Vertex: 1
Visited Vertices
1 2 5 6 3 4
1.DFS
2.BFS
Select Method: 2

Enter no of vertices: 6
Enter no of edges: 6

Enter Edges
1
2
1
3
1
4
2
5
2
6
3
6
Enter Initial Vertex: 1
Visited Vertices
12 3 4 5 6

No comments:

Post a Comment