Pagini recente » Cod sursa (job #1630114) | Cod sursa (job #1279665) | Cod sursa (job #2382186) | Cod sursa (job #1411480) | Cod sursa (job #831915)
Cod sursa(job #831915)
# include <stdio.h>
# include <vector>
//# include <conio.h>
# define N 1000002
using namespace std;
typedef struct Node {
int id;
vector <int> neighbours;
int dist;
};
Node graph[N];
int source, n, m, k = 0;
void readGraph () {
FILE *f;
int x, y;
int ok = 0;
f = fopen("bfs.in", "r");
if (!f){
return;
}
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 < m; 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");
}
}
int bfs (int start, int stop) {
vector <int> queue;
int *visited = (int*)calloc(N,sizeof(int));
queue.push_back(start);
visited[start] = 1;
while (queue.size() > 0) {
int n = queue.at(0);
queue.erase(queue.begin());
if (n == stop){
//printf("Done !\n");
return graph[n].dist;
}
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;
queue.push_back(graph[n].neighbours.at(i));
graph[graph[n].neighbours.at(i)].dist = graph[n].dist + 1;
}
}
}
return -1;
}
int main () {
readGraph();
//printGraph();
FILE *g = fopen ("bfs.out","w");
for (int i = 1; i < n + 1; i++){
int dist = bfs(source, i);
fprintf(g,"%i ", dist);
}
fclose(g);
//getch();
return 0;
}