Pagini recente » Cod sursa (job #464872) | Cod sursa (job #1241038) | Cod sursa (job #45837) | Cod sursa (job #72474) | Cod sursa (job #3156437)
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>
using namespace std;
ifstream f("bfs.in");
ofstream o("bfs.out");
const int nmax = 100000;
vector<int> G[nmax+1];
int vis[nmax+1];
/*void DFS(int x){
vis[x]=1;
for(int i=0; i<G[x].size(); i++)
{
if(!vis[G[x][i]])DFS(G[x][i]);
}
}*/
int d[nmax+1];
void BFS(int x){
queue<int> q;
q.push(x);
d[x]=0;
vis[x] = 1;
while(!q.empty()){
x = q.front();
cout<<x<<" ";
q.pop();
for(auto next:G[x]){
if(!vis[next]){
q.push(next);
vis[next] = 1;
d[next] = d[x] + 1;
}
}
}
}
int main()
{
int n,m,s;
f >> n >> m >> s;
for (int i = 1; i<=m; i++)
{
int x,y;
f>>x>>y;
G[x].push_back(y);
G[y].push_back(x);
}
BFS(s);
for(int i=1; i<=n; i++){
if(i != s && d[i]==0)
o<<"-1";
else
o<<d[i]<<" ";
}
return 0;
}