Pagini recente » Cod sursa (job #262968) | Cod sursa (job #203652) | Cod sursa (job #2275791) | Cod sursa (job #555940) | Cod sursa (job #1424964)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
struct Node {
std::vector<int> neighbours;
bool visited;
int distance;
int id;
Node() {
visited = false;
distance = 0;
}
};
void doBFS (std::vector<Node> &graph, int startingPoint) {
std::queue<Node> q;
q.push (graph[startingPoint]);
graph[startingPoint].visited = true;
while (!q.empty()) {
Node n = q.front();
q.pop();
for (size_t i = 0; i < n.neighbours.size(); ++i) {
if (!graph[n.neighbours[i]].visited) {
graph[n.neighbours[i]].distance = n.distance + 1;
q.push (graph[n.neighbours[i]]);
graph[n.neighbours[i]].visited = true;
}
}
}
}
int main() {
std::ifstream fin ("bfs.in");
std::ofstream fout ("bfs.out");
int numberOfVertiges, numberOfEdges, startingPoint, source, dest;
fin >> numberOfVertiges;
fin >> numberOfEdges;
fin >> startingPoint;
std::vector<Node> graph (numberOfVertiges);
for (int i = 0; i < numberOfEdges; ++i) {
fin >> source;
fin >> dest;
graph[source - 1].neighbours.push_back (dest - 1);
}
for (int i = 0; i < numberOfVertiges; ++i) {
graph[i].id = i;
}
doBFS (graph, startingPoint - 1);
for (int i = 0; i < numberOfVertiges; ++i) {
if (graph[i].distance == 0 && i != startingPoint - 1) {
fout << -1 << " ";
continue;
} else {
fout << graph[i].distance << " ";
}
}
fout.close();
fin.close();
}