Pagini recente » Monitorul de evaluare | Cod sursa (job #1731744) | Cod sursa (job #746645) | Cod sursa (job #388638) | Cod sursa (job #2571856)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream cin("bfs.in");
ofstream cout("bfs.out");
#define MAXN 100005
int n, m, s;
vector<int> graph[MAXN];
queue<int> q;
int dist[MAXN];
void BFS()
{
int nod = q.front();
dist[nod] = 0;
while(!q.empty()) {
for (int i = 0; i < graph[nod].size(); i++) {
if (dist[graph[nod][i]] == -1) {
dist[graph[nod][i]] = dist[nod] + 1;
q.push(graph[nod][i]);
}
}
q.pop();
}
}
int main() {
cin >> n >> m >> s;
int x, y;
for(int i = 0; i < m; i++)
{
cin >> x >> y;
graph[x].push_back(y);
graph[y].push_back(x);
}
for(int i = 1; i <= n; i++)
dist[i] = -1;
q.push(s);
BFS();
for(int i = 1; i <= n; i++)
{
cout << dist[i] << " ";
}
return 0;
}