Pagini recente » Cod sursa (job #1316163) | Cod sursa (job #2269685) | Cod sursa (job #1220490) | Rating Cernea Teodora (funlovinggirl) | Cod sursa (job #3155970)
/*#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("graf.in");
int a[1005][1005];
int n, m;
vector<int> G[1005];
void readListe()
{
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y;
fin >> x >> y;
G[x].push_back(y);
G[y].push_back(x);
}
}
void showNe()
{
for(int i=1;i<=n;i++)
for ( auto x:G[i])
cout << x << " ";
}
void readNeorientat()
{
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y;
fin >> x >> y;
a[x][y] = a[y][x] = 1;
}
}
void readOrientat()
{
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y;
fin >> x >> y;
a[x][y] = 1;
}
}
void show()
{
for (int i = 1; i <= n; i++)
{
for(int j=1; j<=n; j++)
cout << a[i][j] << " ";
cout << endl;
}
}
int main()
{
readListe();
showNe();
return 0;
}
*/
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
#define N 10005
int a[N][N];
int n, m, source;
int viz[N];
void read()
{
fin >> n >> m >> source;
for (int i = 1; i <= m; i++)
{
int x, y;
fin >> x >> y;
a[x][y] = 1;
}
}
void bfs(int x)
{
int c[N], p, u;
p = u = 1;
c[1] = x;
viz[x] = 1;
while (p <= u)
{
int nod = c[p++];
fout << nod << " ";
for (int i = 1; i <= n; i++)
if (a[nod][i] && !viz[i])
{
c[++u] = i;
viz[i] = 1;
}
}
}
//calculate the minimum distance from source to all other nodes
void bfs2(int x)
{
int c[N], p, u;
p = u = 1;
c[1] = x;
viz[x] = 1;
int d[N];
for (int i = 1; i <= n; i++)
d[i] = -1;
d[x] = 0;
while (p <= u)
{
int nod = c[p++];
for (int i = 1; i <= n; i++)
if (a[nod][i] && !viz[i])
{
c[++u] = i;
viz[i] = 1;
d[i] = d[nod] + 1;
}
}
for (int i = 1; i <= n; i++)
fout << d[i] << " ";
}
int main()
{
read();
bfs2(source);
return 0;
}