Pagini recente » Cod sursa (job #2263575) | Cod sursa (job #2556825) | Cod sursa (job #1952961) | tema | Cod sursa (job #1705647)
#include <stdio.h>
#include <string.h>
#include <vector>
#include <queue>
#define MAX_NODES 100000
std::vector<int> adj_list[MAX_NODES + 1];
void bfs(int num_nodes, int depth[], int start_node) {
int curr_node;
std::queue<int> q;
//memset(depth, -1, num_nodes + 1);
for (int i = 1; i <= num_nodes; i++) {
depth[i] = -1;
}
depth[start_node] = 0;
q.push(start_node);
while (!q.empty()) {
curr_node = q.front();
q.pop();
for (auto &adj_node : adj_list[curr_node]) {
if (depth[adj_node] < 0) {
depth[adj_node] = depth[curr_node] + 1;
q.push(adj_node);
}
}
}
}
int main(void) {
FILE * fin = fopen("bfs.in", "r");
FILE * fout = fopen("bfs.out", "w");
int n, m, s, x, y;
fscanf(fin, "%d%d%d", &n, &m, &s);
int depth[n + 1];
for (int i = 0; i < m; i++) {
fscanf(fin, "%d%d", &x, &y);
adj_list[x].push_back(y);
}
bfs(n, depth, s);
for (int i = 1; i <= n; i++) {
fprintf(fout, "%d ", depth[i]);
}
fclose(fin);
fclose(fout);
}