Example 1 — Build and print a matrix
Four vertices and four edges.
#include <stdio.h>
#define V 4
int main(void) {
int m[V][V] = {{0}};
int edges[][2] = {{0, 1}, {0, 2}, {1, 2}, {2, 3}};
for (int i = 0; i < 4; i++) {
m[edges[i][0]][edges[i][1]] = 1;
m[edges[i][1]][edges[i][0]] = 1;
}
for (int u = 0; u < V; u++) {
for (int v = 0; v < V; v++) printf("%d%s", m[u][v], v + 1 < V ? " " : "");
printf("\n");
}
printf("neighbors of 2:");
for (int v = 0; v < V; v++) if (m[2][v]) printf(" %d", v);
printf("\n");
return 0;
} How It Works
- Each edge sets two symmetric cells.
- Row 2 has ones at columns 0, 1, and 3.
- Scanning a row lists a vertex's neighbors.
