Pagini recente » Cod sursa (job #1660733) | Cod sursa (job #406631) | Cod sursa (job #958818) | Cod sursa (job #474857) | Cod sursa (job #2792064)
#include <bits/stdc++.h>
#define NMax 100001
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
class graf
{
int nrNoduri, nrMuchii;
bool orientat;
vector <int> gr[NMax]; // liste de adiacenta
public:
graf(int n, int m, bool o); // constructor
void Citire_Orientat();
void Citire_Neorientat();
void BFS(int s); // s - nodul de start
};
graf :: graf(int n, int m, bool o)
{
nrNoduri = n;
nrMuchii = m;
orientat = o;
}
void graf :: Citire_Orientat()
{
for(int i = 1; i <= nrMuchii; ++i)
{
int x, y;
fin >> x >> y;
gr[x].push_back(y);
}
}
void graf :: Citire_Neorientat()
{
for(int i = 1; i <= nrMuchii; ++i)
{
int x, y;
fin >> x >> y;
gr[x].push_back(y);
gr[y].push_back(x);
}
}
void graf :: BFS(int s)
{
bool viz[NMax] = {0};
int distanta[NMax] = {0};
queue <int> q;
viz[s] = 1;
q.push(s);
while(!q.empty())
{
int k = q.front(); // elem din varful cozii
q.pop(); // sterg elem din varful cozii
for(auto i : gr[k])
if(!viz[i])
{
viz[i] = 1;
q.push(i);
distanta[i] = distanta[k] + 1;
}
}
for(int i = 1; i <= nrNoduri; ++i)
if(viz[i])
fout << distanta[i] << " ";
else
fout << -1 << " ";
}
int nrNoduri, nrMuchii, s; // s - nodul sursa
int main()
{
fin >> nrNoduri >> nrMuchii >> s;
graf G(nrNoduri, nrMuchii, 1);
G.Citire_Orientat();
G.BFS(s);
return 0;
}