Skip to content

Update bfs.cpp #9

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

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
96 changes: 96 additions & 0 deletions Graphs1/bfs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ Note : Take graph input in adjacency matrix.
Input Format :
Line 1: Two Integers V and E (separated by space)
Next 'E' lines, each have two space-separated integers, 'a' and 'b', denoting that there exists an edge between Vertex 'a' and Vertex 'b'.
Note : 1. Take graph input in the adjacency matrix.
2. Handle for Disconnected Graphs as well
Input Format :
Output Format :
BFS Traversal (separated by space)
Constraints :
Expand All @@ -28,6 +31,99 @@ Sample Output 1:
0 1 3 2
*/



/*
Contributer: Bhavya Tyagi
Thapar Institute of Engineering & Technology, Patiala
Added The Modified code after the question includes Disconnected Graphs too
*/

#include <iostream>
#include <queue>
using namespace std;

void printBFS(int **edges,int n, int j,bool *visited)
{

queue <int> q;
q.push(j);
visited[j]=true;
while(!q.empty())
{
int currentEdge=q.front();
cout<<currentEdge<<" ";
q.pop();
for(int i=0;i<n;i++)
{
if(i==currentEdge)
continue;
if(edges[currentEdge][i]&&!visited[i])
{
q.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;
}

int main()
{
int n,e;
cin>>n>>e;

int **edges=new int*[n];

for(int i=0;i<n;i++)
{
edges[i]=new int[n];
for(int j=0;j<n;j++)
edges[i][j]=0;
}
for(int i=0;i<e;i++)
{
int f,s;
cin>>f>>s;
edges[f][s]=1;
edges[s][f]=1;
}
bool *visited=new bool[n];

for(int i=0;i<n;i++)
visited[i]=false;


BFS(edges,n);


return 0;
}




/*

Old code without Disconnected Graphs (Only 50% Testcase Passes with the old code)
by Mehul Chaturvedi
*/

#include <bits/stdc++.h>

using namespace std;
Expand Down