BFS WITH LEBEL
#include<bits/stdc++.h>
using namespace std;
int graph[100][100],v;
void bfs(int src)
{
int lebel[v+1],i,rem;
for(i=1;i<=v;i++) lebel[i]=-1;
lebel[src]=0;
int visited[v+1];
for(i=1;i<=v;i++) visited[i]=0; ///no vertex is visited yet
visited[src]=1;
queue<int> q;
q.push(src);
while(!q.empty())
{
rem=q.front();
cout<<rem<<" ";
q.pop();
for(i=1;i<=v;i++)
{
if(graph[rem][i]==1 && visited[i]==0)
{
lebel[i]=lebel[rem]+1;
cout<<i<<" ";
q.push(i);
visited[i]=1;
}
}
}
cout<<endl;
for(i=1;i<=v;i++)
cout<<lebel[i]<<" ";
}
int main()
{
int i,j;
cin>>v;
for(i=1;i<=v;i++)
for(j=1;j<=v;j++)
cin>>graph[i][j];
bfs(1);
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int graph[100][100],v;
void bfs(int src)
{
int lebel[v+1],i,rem;
for(i=1;i<=v;i++) lebel[i]=-1;
lebel[src]=0;
int visited[v+1];
for(i=1;i<=v;i++) visited[i]=0; ///no vertex is visited yet
visited[src]=1;
queue<int> q;
q.push(src);
while(!q.empty())
{
rem=q.front();
cout<<rem<<" ";
q.pop();
for(i=1;i<=v;i++)
{
if(graph[rem][i]==1 && visited[i]==0)
{
lebel[i]=lebel[rem]+1;
cout<<i<<" ";
q.push(i);
visited[i]=1;
}
}
}
cout<<endl;
for(i=1;i<=v;i++)
cout<<lebel[i]<<" ";
}
int main()
{
int i,j;
cin>>v;
for(i=1;i<=v;i++)
for(j=1;j<=v;j++)
cin>>graph[i][j];
bfs(1);
return 0;
}
Comments
Post a Comment