Pagini recente » Cod sursa (job #2399991) | Cod sursa (job #2170009) | Cod sursa (job #762926) | Cod sursa (job #2796161) | Cod sursa (job #831935)
Cod sursa(job #831935)
# include <stdio.h>
# include <vector>
# include <queue>
//# include <conio.h>
# include <stdlib.h>
# define N 1000020
using namespace std;
typedef struct Node {
int id;
vector <int> neighbours;
int dist;
};
Node graph[N];
int visited[N];
int source, n, m;
void readGraph () {
FILE *f;
int x, y;
f = fopen("bfs.in", "r");
fscanf(f, "%i %i %i", &n, &m, &source);
for (int i = 0; i < m; i++) {
fscanf (f, "%i %i",&x, &y);
graph[x].id = x;
graph[x].neighbours.push_back(y);
graph[x].dist = 0;
}
fclose(f);
}
void printGraph () {
for (int i = 1; i <= n; i++){
printf("%i: ", graph[i].id);
for (int j = 0; j < graph[i].neighbours.size(); j++){
printf("%i ", graph[i].neighbours.at(j));
}
printf("\n");
}
}
void bfs (int start) {
queue <int> my_queue;
my_queue.push(start);
visited[start] = 1;
while (!my_queue.empty()) {
int n = my_queue.front();
my_queue.pop();
for (int i = 0; i < graph[n].neighbours.size(); i++){
if (visited[graph[n].neighbours.at(i)] == 0){
visited[graph[n].neighbours.at(i)] = 1;
my_queue.push(graph[n].neighbours.at(i));
graph[graph[n].neighbours.at(i)].dist = graph[n].dist + 1;
}
}
}
}
int main () {
readGraph();
//printGraph();
bfs(source);
FILE *g = fopen ("bfs.out","w");
for (int i = 1; i < n + 1; i++){
if (i != source && graph[i].dist == 0)
fprintf(g, "-1 ");
else
fprintf(g,"%i ", graph[i].dist);
}
fclose(g);
//getch();
return 0;
}