Data Structures
Data Structures
Experiment -3.3
Algorithm:
i) Start
ii) Take number of vertices and edges as input from user.
iii) Make an adjacency matrix of edges.
iv) Now call a dfs and bfs function which will print the graph in depth-first
search and breadth first search. v) End
Program code:
#include<iostream>
#include<queue>
using namespace std;
void printBFS(int** edges, int n, int sv, bool* visited)
{ queue<int> pendingVertices;
pendingVertices.push(sv); visited[sv]
= true;
while(!pendingVertices.empty())
{
int currentVertex = pendingVertices.front();
pendingVertices.pop(); cout <<
currentVertex << endl; for(int i=0; i < n;
i++){
if(i == currentVertex)
{ continue;
}
if(edges[currentVertex][i] == 1 && !visited[i])
{
pendingVertices.push(i);
visited[i] = true;
}
}
}
}
void BFS(int** edges, int n)
{ bool* visited = new bool[n];
for(int i=0; i<n; i++)
{ visited[i] = false;
} for(int i=0; i < n;
i++)
{ if(!visited[i])
{ printBFS(edges, n, i, visited);
}
}
delete [] visited;
// DFS
Output: