Untitled
unknown
plain_text
4 years ago
2.4 kB
7
Indexable
#include<stdio.h> typedef struct{ int data[100]; int size; }List; void makenull_list(List *pL) { pL->size=0; } void pushback(List *pL, int x) { pL->data[pL->size]=x; pL->size++; } int element_at(List *pL, int i) { return pL->data[i-1]; } void print_list(List *pL) { int i; for(i=1; i<=pL->size; i++) { printf("%d ", element_at(pL, i)); } } typedef struct { int A[20][20]; int n; //So luong dinh }Graph; void init_graph(Graph *pG, int n) { int i, j; pG->n=n; for(i=1; i<=n; i++) { for(j=1; j<=n; j++) pG->A[i][j]=0; } } void add_edge(Graph *pG, int x, int y) { pG->A[x][y]=1; pG->A[y][x]=1; } //Kiem tra lang gieng x, y phai lang gieng khong? int adjecent(Graph *pG, int x, int y) { return pG->A[x][y]; } void print_graph(Graph *pG) { int i, j; for(i=1; i<=pG->n; i++) { for(j=1; j<=pG->n; j++) printf("%d ", pG->A[i][j]); printf("\n"); } } List neighbors(Graph *G, int x) { int i; List list; makenull_list(&list); for(i=1; i<=G->n; i++) if(adjecent(G, x, i)==1) pushback(&list, i); return list; } typedef struct { int data[100]; int front, rear; } Queue; void make_null_queue(Queue* Q) { Q->front = 0; Q->rear = -1; } void push(Queue* Q, int x) { Q->rear++; Q->data[Q->rear] = x; } int top(Queue* Q) { return Q->data[Q->front]; } void pop(Queue* Q) { Q->front++; } int empty(Queue* Q) { return Q->front > Q->rear; } void breath_first_search(Graph* G) { Queue frontier; int mark[100]; make_null_queue(&frontier); /* Kh?i t?o mark, chua d?nh nào du?c xét */ int j; for (j = 1; j <= G->n; j++) mark[j] = 0; /* Ðua 1 vào frontier */ push(&frontier, 1); mark[1] = 1; /* Vòng l?p chính dùng d? duy?t */ while (!empty(&frontier)) { /* L?y ph?n t? d?u tiên trong frontier ra */ int x = top(&frontier); pop(&frontier); printf("%d\n", x); /* L?y các d?nh k? c?a nó */ List list = neighbors(G, x); /* Xét các d?nh k? c?a nó */ for (j = 1; j <= list.size; j++) { int y = element_at(&list, j); if (mark[y] == 0) { mark[y] = 1; push(&frontier, y); } } } } int main() { //freopen("dt.txt", "r", stdin); int i, n, m, u, v; Graph G; scanf("%d%d", &n, &m); init_graph(&G, n); for(i=1; i<=m; i++) { scanf("%d%d", &u, &v); add_edge(&G, u, v); } //print_graph(&G); breath_first_search(&G); return 0; }
Editor is loading...