Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create bfs.cpp #63

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions codes/bfs.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

vector<int>v[100007];
int visited[100007];
int main(){
int n,m;
cout<<"Enter the number of vertices and edges: \n";
cin>>n>>m;

cout<<"Enter the edges of the graph or tree \n";
for(int i=0;i<m;i++){
int x,y;
cin>>x>>y;
v[x].push_back(y);
v[y].push_back(x);
}

int src;
cout<<"Enter the source vertex: \n";
cin>>src;

queue<int>bfs;
bfs.push(src);

cout<<"BFS TRAVERSAL: \n";
while(!bfs.empty()){
int temp=bfs.front();
cout<<temp<<" ";
visited[temp]=1;
bfs.pop();

for(int i=0;i<v[temp].size();i++){
int te=v[temp][i];
if(!visited[te]){
bfs.push(te);
visited[te]=1;
}
}
}
return 0;
}


/* Sample Test Case

Enter the number of vertices and edges:
5 4
Enter the edges of the graph or tree
1 2
2 4
1 3
2 5
Enter the source vertex:
1
BFS TRAVERSAL:
1 2 3 4 5

*/