Pagini recente » Cod sursa (job #1936136) | Cod sursa (job #2370871) | Cod sursa (job #5274) | Cod sursa (job #387874) | Cod sursa (job #3155958)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream in("bfs.in");
ofstream out("bfs.out");
const int NMAX = 1e5;
int d[NMAX+1];
bool vis[NMAX+1];
queue<int > q;
vector <int> G[NMAX+1];
//bool a[NMAX+1][NMAX+1];
void BFS(int x)
{
q.push(x);
d[x] = 0;
vis[x] = true;
while(!q.empty())
{
int y = q.front();
q.pop();
for(auto i : G[y])
{
if(!vis[i])
{
q.push(i);
vis[i] = true;
d[i] = d[y] + 1;
}
}
}
}
int main(int argc, const char * argv[])
{
int n,m,s;
in >> n >> m >> s;
// for(int i = 0; i < n; i++) //citire in matrice de aficienta
// {
// int x,y;
// in >> x >> y;
// a[x][y] = a[y][x] = true;
// }
for(int i = 0; i < m; i++) //citire in liste de adiacenta
{
int x,y;
in >> x >> y;
G[x].push_back(y);
}
BFS(s);
for(int i = 1 ; i <= n; i++)
{
if(d[i] == 0 && i != s)
{
d[i] = -1;
}
out << d[i] << " ";
}
// for(int i = 0; i < n; i++)
// {
// for(auto x: G[i])
// {
// cout << x << " ";
// }
// }
// for(int i = 0; i < n; i++)
// {
// for(int j = 0; j < n; j++)
// {
// cout << a[i][j] << " ";
// }
// cout << "\n";
// }
return 0;
}