master
 1#include <stdio.h>
 2#include <stdlib.h>
 3
 4char labels[26] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
 5                   'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
 6                   's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
 7
 8/**
 9 * Traverses a graph represented as an adjacency matrix
10 * to visit every vertex in the graph and traverse each
11 * edge in both directions only once.
12 *
13 * @param n The # of vertexes in the graph
14 * @param graph An adjacency matrix that represents the graph
15 * @param visited An array that keeps track of which vertexes have been visited
16 * @param vertex The current vertex to traverse.
17 */
18void matrix_traverse(int n, int graph[n][n], int visited[n], int vertex) {
19  printf("->(%c)", labels[vertex]);
20  visited[vertex] = 1;
21
22  for (int edge = 0; edge < n; ++edge) {
23    if (!visited[edge] && graph[vertex][edge] > 0) {
24      graph[vertex][edge] = 0;
25      matrix_traverse(n, graph, visited, edge);
26      graph[edge][vertex] = 0;
27      printf("->(%c)", labels[vertex]);
28    }
29  }
30  for (int edge = 0; edge < n; ++edge) {
31    if (graph[vertex][edge] > 0 && graph[edge][vertex] > 0) {
32      graph[vertex][edge] = 0;
33      matrix_traverse(n, graph, visited, edge);
34      graph[edge][vertex] = 0;
35      printf("->(%c)", labels[vertex]);
36    }
37  }
38}
39
40/**
41 * Prints a visual representation of an
42 * adjacency matrix to stdout out for debugging purposes.
43 *
44 * @param n The number of vertexes in the graph.
45 * @param graph The adjacency matrix that represents the graph.
46 */
47void matrix_inspect(int n, int graph[n][n]) {
48  printf("\n");
49
50  printf("| ");
51  for (int i = 0; i < n; ++i)
52    printf("|%c", labels[i]);
53  printf("|\n");
54
55  for (int i = 0; i < n; ++i) {
56    printf("|%c|", labels[i]);
57    for (int j = 0; j < n; ++j)
58      printf("%d|", graph[i][j]);
59    printf("\n");
60  }
61}