You are on page 1of 4

Q//

Write a program to traverse a graph data structure


using queue and stack data structure

BFS:
BFS stands for Breadth First Search is a vertex based technique for finding a shortest path in graph. It
uses a Queue data structure which follows first in first out. In BFS, one vertex is selected at a time when
it is visited and marked then its adjacent are visited and stored in the queue.

DFS:
DFS stands for Depth First Search is a edge based technique. It uses the Stack data structure, performs
two stages, first visited vertices are pushed into stack and second if there is no vertices then visited
vertices are popped. 

CODE:
//implementing BFS and DFS

#include<iostream>

#include<vector>

#include<queue>

#include<stack>

using namespace std;

void edge(vector<int>adj[],int u,int v){

adj[u].push_back(v);

//bfs uses queue data structure


void bfs(int s,vector<int>adj[],bool visit[]){

//using a queue

queue<int>q;

q.push(s);

visit[s]=true;

while(!q.empty()){

int u=q.front();

cout<<u<<" ";

q.pop();

//loop for traverse

for(int i=0;i<adj[u].size();i++){

if(!visit[adj[u][i]]){

q.push(adj[u][i]);

visit[adj[u][i]]=true;

//bfs uses queue data structure

void dfs(int s,vector<int>adj[],bool visit[]){

//using a stack

stack<int>stk

stk.push(s);

visit[s]=true;

while(!stk.empty()){
int u=stk.top();

cout<<u<<" ";

stk.pop();

//loop for traverse

for(int i=0;i<adj[u].size();i++){

if(!visit[adj[u][i]]){

stk.push(adj[u][i]);

visit[adj[u][i]]=true;

//main function

int main(){

vector<int>adj[5];

bool visit[5];

//initially all node are unvisited

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

visit[i]=false;

//input for edges

edge(adj,0,2);

edge(adj,0,1);

edge(adj,1,3);

edge(adj,2,0);
edge(adj,2,3);

edge(adj,2,4);

cout<<"BFS traversal is"<<" ";

bfs(0,adj,visit);//1 is a starting point

cout<<endl;

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

visit[i]=false;

cout<<"DFS traversal is"<<" ";

dfs(0,adj,visit);//1 is a starting point

OUTPUT:

You might also like