Pagini recente » Cod sursa (job #2102795) | Cod sursa (job #1059825) | Cod sursa (job #356848) | Cod sursa (job #3156238) | Cod sursa (job #2541775)
#include <bits/stdc++.h>
#define nmax 100005
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
vector <int> graphs[nmax];
queue <int> noduri;
int n, m, distanta[nmax];
bool vizat[nmax];
void bfs(int nod_start)
{
vizat[nod_start] = 1;
noduri.push(nod_start);
unsigned len, i;
int nod;
while(!noduri.empty())
{
nod = noduri.front();
noduri.pop();
len = graphs[nod].size();
for(i = 0; i < len; i++)
{
if(!vizat[graphs[nod][i]])
{
distanta[graphs[nod][i]] = distanta[nod] + 1;
vizat[graphs[nod][i]] = 1, noduri.push(graphs[nod][i]);
}
}
}
}
int main()
{
int first, i, x, y;
fin >> n >> m >> first;
for(i = 0; i < m; i++)
fin >> x >> y, graphs[x].push_back(y);
bfs(first);
for(i = 1; i <= n; i++)
{
if(distanta[i])
fout << distanta[i] << ' ';
else if(i == first)
fout << distanta[i] << ' ';
else
fout << "-1 ";
}
return 0;
}