Skip to content

Instantly share code, notes, and snippets.

@abhagsain
Created April 30, 2019 02:58
Show Gist options
  • Select an option

  • Save abhagsain/cbcc2b45728cce84372868c82df7db02 to your computer and use it in GitHub Desktop.

Select an option

Save abhagsain/cbcc2b45728cce84372868c82df7db02 to your computer and use it in GitHub Desktop.
BFS & DFS
/*
Write a BFS program using adjacency list and queue
*/
#include<iostream>
#include<list>
#include<queue>
#include<stack>
using namespace std;
class Graph{
private:
int numberOfVertices;
list<int> *adjList;
public:
Graph(int size){
numberOfVertices = size;
adjList = new list <int> [size];
}
void addVertices(int v1, int v2){
if(v1 <= numberOfVertices && v2 <= numberOfVertices){
adjList[v1].push_back(v2);
adjList[v2].push_back(v1);
}else return;
}
void show(){
list<int>:: iterator i;
for(int j = 0; j < numberOfVertices; j++){
cout<<j;
for(i = adjList[j].begin(); i != adjList[j].end(); ++i){
cout<<" -> "<<*i;
}
cout<<endl;
}
}
void bfs(){
queue<int> queue;
bool isVisited [numberOfVertices] = {false};
// for(int i = 0; i < numberOfVertices; i++) isVisited[i] = false;
queue.push(0);
isVisited[0] = true;
list<int>:: iterator i;
cout<<"\nBFS \n";
while(!queue.empty()){
int item = queue.front();
queue.pop();
for(i = adjList[item].begin(); i != adjList[item].end(); i++){
if(!isVisited[*i]){
queue.push(*i);
isVisited[*i] = true;
}
}
cout<<item<<" ";
}
}
void dfs(){
cout<<"\nDFS ";
bool isVisited [numberOfVertices];
for(int i = 0; i < numberOfVertices; i++) isVisited[i] = false;
dfs(0,isVisited);
}
void dfs(int el, bool isVisited []){
cout<<" "<<el;
isVisited[el] = true;
list<int> ::iterator i;
for(i = adjList[el].begin(); i != adjList[el].end(); i++){
if(!isVisited[*i]){
dfs(*i,isVisited);
}
}
}
};
int main(){
int size;
cout<<"\nEnter number of vertices ";
cin>>size;
Graph g(size);
cout<<"\nStart entering edge from one vertex to another eg. 0 -> 2";
for(int i = 0; i < size; i++){
cout<<"\nEnter starting vertex ";
int start;
cin>>start;
cout<<"\nEnter ending vertex ";
int end;
cin>>end;
g.addVertices(start,end);
}
g.show();
g.bfs();
g.dfs();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment