Pagini recente » Cod sursa (job #2697637) | Cod sursa (job #2801896) | Cod sursa (job #2439463) | Cod sursa (job #2545972) | Cod sursa (job #3165866)
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <fstream>
#include <map>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
vector<int> graf[100001];
int n, m, s;
map<int, bool> visited;
int dist[100001];
queue<pair<int, int>> q;
int bfs()
{
q.push({s, 0});
visited[s] = true;
int cNode, pas;
while (!q.empty())
{
cNode = q.front().first;
pas = q.front().second + 1;
dist[cNode] = pas - 1;
for (int i = 0; i < graf[cNode].size(); i++)
{
if (!visited.count(graf[cNode][i]))
{
visited[graf[cNode][i]] = true;
q.push({graf[cNode][i], pas});
}
}
q.pop();
}
return -1;
}
int main()
{
fin >> n >> m >> s;
int x, y;
for (int i = 0; i < m; i++)
{
fin >> x >> y;
graf[x].push_back(y);
}
for (int i = 1; i <= n; i++)
{
dist[i] = -1;
}
bfs();
for (int i = 1; i <= n; i++)
{
fout << dist[i] << ' ';
}
return 0;
}