Topics / Data Structures & Algorithms / Q20
Parse an edge list into a graph in C.
Short answer: Read each pair of vertex IDs, validate it, and set the corresponding adjacency-matrix entry. This example accepts an already-tokenized list of directed edges.
#include <stdbool.h>
#include <stddef.h>
#include <string.h>
#define N 8
struct edge { int from, to; };
bool parse_graph(bool g[N][N], const struct edge *e,
size_t count)
{
for (size_t i = 0; i < count; i++)
if (e[i].from < 0 || e[i].from >= N ||
e[i].to < 0 || e[i].to >= N)
return false;
memset(g, 0, N * sizeof g[0]);
for (size_t i = 0; i < count; i++)
g[e[i].from][e[i].to] = true;
return true;
}
Example edges {0,1}, {0,2}, {2,3} describe 0→1, 0→2 and 2→3. For undirected edges set the reverse entry too. If parsing text, use checked integer conversion and reject malformed or out-of-range tokens before calling this function. Time O(N²+E); adjacency lists are more memory-efficient for sparse topologies.