Pagini recente » Cod sursa (job #358761) | Cod sursa (job #1913831) | Cod sursa (job #2583679) | Cod sursa (job #1693350) | Cod sursa (job #2909945)
#include <iostream>
#include <fstream>
#include <cmath>
#include <queue>
using namespace std;
void bfs(int** a,int n,int v[],int h)
{
queue <int> q;
h--;
q.push(h);
int cnt=0;
v[h]=cnt;
bool ext=false;
cnt++;
while(!q.empty())
{
ext=false;
for(int i=0;i<n;++i)
if(a[q.front()][i]==1 and v[i]==-1)
{
q.push(i);
v[i]=cnt;
ext=true;
}
if(ext) cnt++;
q.pop();
}
}
int main()
{
ifstream reader("bfs.in");
ofstream writer("bfs.out");
int n,m;
int h;
reader>>n>>m>>h;
int** a = new int*[n];
for(int i=0;i<n;++i)
a[i] = new int[n];
for(int i=0;i<n;++i)
for(int j=0;j<n;++j)
a[i][j]=0;
int x,y;
for(int i=0;i<m;++i)
{
reader>>x>>y;
x--;
y--;
a[x][y]=1;
}
int v[n];
for(int i=0;i<n;++i)
v[i]=-1;
bfs(a,n,v,h);
for(int i=0;i<n;++i)
writer<<v[i]<<" ";
return 0;
}