#include #include #include typedef int T; typedef struct queue_s { T *body; T *begin; T *end; T *body_end; } queue; queue* queue_new(size_t size) { queue *t = (queue *)malloc(sizeof(queue)); assert(t != NULL); t->body = (int *)malloc(sizeof(T)*size); t->begin = t->end = t->body; t->body_end = t->body + size; return t; } void queue_delete(queue *t) { free(t->body); free(t); } void queue_enqueue(queue *t, T el) { assert(t->end < t->body_end); *t->end++ = el; } int queue_empty(queue const *t) { return t->begin == t->end; } T queue_dequeue(queue *t) { return *t->begin++; } typedef enum color_t { WHITE, GREY, BLACK } color; // unweighted graph typedef struct graph_t { char *neibs; // 2-d linear matrix size_t N; int unordered; } graph; graph *graph_new(size_t nodes, int is_ordered) { graph *t = (graph *) malloc(sizeof(graph)); t->N = nodes; t->unordered = !is_ordered; t->neibs = (char *) calloc(sizeof(char), nodes * nodes); return t; } void graph_delete(graph *g) { free(g->neibs); free(g); } void graph_add_edge(graph *t, int from, int to) { t->neibs[from * t->N + to] = 1; if (t->unordered) { t->neibs[to * t->N + from] = 1; } } // Perform BFS search. // Input: s - start node // Output: vector of distances void graph_bfs(graph* t, int s, int *d) { assert (s >= 0 && s < t->N); color *c = (color *)calloc(sizeof(color),t->N); for (int i = 0; i < t->N; i++) d[i] = -1; queue *q = queue_new(t->N*t->N); queue_enqueue(q, s); d[s] = 0; c[s] = GREY; while (!queue_empty(q)) { int u = queue_dequeue(q); for (int z = 0; z < t->N; z++) { if (t->neibs[u*t->N+z] == 0 || c[z] != WHITE) continue; d[z] = d[u] + 1; c[z] = GREY; queue_enqueue(q, z); } c[u] = BLACK; } queue_delete(q); free(c); } int main() { int n, e; scanf("%d %d", &n, &e); graph *g = graph_new(n, 0); for (int i = 0; i < e; i++) { int from,to; scanf("%d %d", &from, &to); graph_add_edge(g, from,to); } int *d = (int *)malloc(sizeof(int) * n); graph_bfs(g, 0, d); for (int i = 0; i < n; i++) { printf("%d ", d[i]); } printf("\n"); free(d); graph_delete(g); } #if 0 Вариант входных данных 7 8 0 1 1 2 2 4 2 6 0 3 3 4 2 5 4 6 #endif