#include #include #include typedef struct Node node; struct Node { int vertex; struct Node *next; }; typedef struct List list; struct List { node *head; node *tail; }; typedef struct Graph graph; struct Graph { int nvertices; int *visited; list *vertices; }; graph *init_graph(int n) { graph *graph = malloc(sizeof(struct Graph)); graph->nvertices = n; graph->vertices = malloc(n * sizeof(struct List)); graph->visited = malloc(n * sizeof(int)); memset(graph->visited, 0, sizeof(int) * n); return graph; } void insert(list *list, int vertex) { node *new = malloc(sizeof(struct Node)); new->next = NULL; new->vertex = vertex; if (!list->head) list->head = list->tail = new; else list->tail->next = new, list->tail = new; } void pop(list *list) { if (!list->head) return; node *next = list->head->next; free(list->head); if (!next) list->tail = next; list->head = next; } void add_edge(graph *graph, int src, int dst) { insert(&graph->vertices[src], dst); insert(&graph->vertices[dst], src); } void dfs(struct Graph *graph, int vertex) { list list = graph->vertices[vertex]; printf("%d ", vertex); graph->visited[vertex] = 1; node *cur = list.head; while (cur) { if (!graph->visited[cur->vertex]) dfs(graph, cur->vertex); cur = cur->next; } } void bfs(struct Graph *graph, int _vertex) { list next; next.head = next.tail = NULL; graph->visited[_vertex] = 1; insert(&next, _vertex); while (next.head) { int vertex = next.head->vertex; list list = graph->vertices[vertex]; node *cur = list.head; printf("%d ", vertex); pop(&next); while (cur) { if (!graph->visited[cur->vertex]) { graph->visited[cur->vertex] = 1; insert(&next, cur->vertex); } cur = cur->next; } } } int main() { const int ROOT = 0; const int SIZE = 5; struct Graph *graph = init_graph(SIZE); add_edge(graph, 0, 1); add_edge(graph, 0, 3); add_edge(graph, 0, 4); add_edge(graph, 2, 3); add_edge(graph, 1, 3); printf("DFS: "); dfs(graph, ROOT); printf("\n"); memset(graph->visited, 0, sizeof(int) * graph->nvertices); printf("BFS: "); bfs(graph, ROOT); printf("\n"); // free for (int i = 0; i < graph->nvertices; i++) while(graph->vertices[i].head) pop(&graph->vertices[i]); free(graph->visited); free(graph->vertices); free(graph); return 0; }