Pagini recente » Cod sursa (job #2305801) | Cod sursa (job #1113578) | Cod sursa (job #1495039) | Cod sursa (job #2388714) | Cod sursa (job #2325776)
#include <fstream>
#include <list>
#include <vector>
#include <deque>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
const int maxV = 1e5;
list <int> adjList[1 + maxV];
vector <int> dist;
int V, E, S;
void readData() {
fin >> V >> E >> S;
for (; E; --E) {
int from, to;
fin >> from >> to;
adjList[from].push_back(to);
}
}
void BFS() {
dist.resize(1 + V);
fill(dist.begin(), dist.end(), -1);
dist[S] = 0;
deque <int> Queue;
Queue.push_back(S);
while (!Queue.empty()) {
int node = Queue.front();
Queue.pop_front();
for(const int &nextNode : adjList[node])
if (dist[nextNode] == -1) {
Queue.push_back(nextNode);
dist[nextNode] = dist[node] + 1;
}
}
}
int main() {
readData();
BFS();
for (int node = 1; node <= V; ++node)
fout << dist[node] << ' ';
}