#include <stdlib.h> #include <stdio.h> /* * Adjacency list for a graph of 10 nodes */ struct s_adjlist { int node; struct s_adjlist *next; }; static struct s_adjlist *adj[10]; static int visited[10]; /* * Visit the nodes starting from node printing their value using * depth first search */ static void visit(int node) { struct s_adjlist *p; visited[node] = 1; printf("%d\n", node); for (p = adj[node]; p != NULL; p = p->next) if (!visited[p->node]) visit(p->node); } main() { int a, b; struct s_adjlist *p; int i; /* Read edges and connect them */ while (scanf("%d %d", &a, &b) == 2) { p = (struct s_adjlist *)malloc(sizeof(struct s_adjlist)); p->node = b; p->next = adj[a]; adj[a] = p; p = (struct s_adjlist *)malloc(sizeof(struct s_adjlist)); p->node = a; p->next = adj[b]; adj[b] = p; } /* Depth first search/print of the graph */ for (i = 0; i < 10; i++) visited[i] = 0; for (i = 0; i < 10; i++) if (!visited[i]) visit(i); }Αν το πρόγραμμα διαβάσει το γράφο:
2 3 3 8 8 6 4 9θα τυπώσει την παρακάτω σειρά επίσκεψης:
0 1 2 3 8 6 4 9 5 7