Pagini recente » Istoria paginii runda/simulare-oji-matei-2/clasament | Cod sursa (job #862446) | Cod sursa (job #2457484) | Cod sursa (job #2540840) | Cod sursa (job #2785235)
#include <iostream>
#include<fstream>
#include<vector>
#include<queue>
#define N 100005
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
queue<int> q;
class Graph {
private:
int n, m;
vector<int> adlist[N];
bool viz[N] = {0};
int dist[N] = {0};
public:
void readOriented();
Graph(int n, int m):n(n), m(m){}
void bfs(int first);
void printDist();
};
void Graph::printDist()
{
int i;
for(i = 1; i <= n; ++i)
fout << dist[i] - 1 << " ";
}
void Graph::readOriented()
{
int i, x, y;
for(i = 1; i <= m; ++i)
{
fin >> x >> y;
adlist[x].push_back(y);
}
}
void Graph::bfs(int first){
int node, i, dim;
dist[first] = 1;
viz[first] = 1;
q.push(first);
while(!q.empty())
{
node = q.front();
q.pop();
dim = adlist[node].size();
for(i = 0; i < dim; ++i)
if(!viz[adlist[node][i]])
{
cout << adlist[node][i] <<" ";
viz[adlist[node][i]] = 1;
dist[adlist[node][i]] = dist[node] + 1;
q.push(adlist[node][i]);
}
}
}
int main()
{
int i, first, n, m;
fin >> n >> m >> first;
Graph g(n, m);
g.readOriented();
g.bfs(first);
g.printDist();
return 0;
}