Implementing a Graph Using an Adjacency Matrix in C
Graphs model relationships between objects. A vertex can represent a location, user, web page, computer, or station, while an edge describes a connection between two vertices. This makes graphs useful for route planning, social networks, dependency analysis, and many algorithmic problems.
An adjacency matrix is one of the clearest ways to store a graph in C. It uses a two-dimensional array in which the value at row i and column j records whether an edge connects vertex i to vertex j. With a small, fixed number of vertices, this representation is simple and efficient.
This approach is particularly suitable for learning because the matrix mirrors the mathematical definition of a graph. It also makes operations such as checking whether an edge exists straightforward. The trade-off is that the matrix reserves space for every possible pair of vertices, including pairs that have no connection.
The examples below use C concepts such as arrays, functions, pointers, and dynamic memory. They focus on an unweighted graph first, then explain how the same structure can support directed and weighted connections.
Choosing An Adjacency Matrix
For a graph with V vertices, an adjacency matrix contains V × V entries. If matrix[i][j] is 1, an edge runs from vertex i to vertex j; if it is 0, no edge is present. Vertices are commonly numbered from 0 to V - 1, which fits naturally with C array indexing.
An undirected graph has a symmetric matrix. Adding an edge from vertex 2 to vertex 5 also adds an edge from 5 to 2, so both matrix[2][5] and matrix[5][2] become 1. In a directed graph, these entries can differ because an edge may point in only one direction.
The representation works well when the graph is dense or when the number of vertices is small. A university timetable, a road network between a limited set of suburbs, or connections between a small set of ASX market sectors may be easier to inspect as a matrix. For very sparse graphs with thousands of vertices, an adjacency list usually uses memory more effectively. Related graph concepts and algorithms are collected in the algorithms guide.
Designing The C Data Structure
A basic graph structure can store the number of vertices and a pointer to the matrix:
typedef struct {
int vertices;
int **matrix;
} Graph;
The int **matrix field will point to an array of row pointers. Each row will then point to an array of integers. This design allows the matrix size to be selected at runtime rather than fixed at compile time.
For a small teaching example, a fixed array is also possible:
#define MAX_VERTICES 10
int matrix[MAX_VERTICES][MAX_VERTICES] = {0};
The fixed form is easier to read, but it limits the graph to MAX_VERTICES vertices. Dynamic allocation is more reusable because a program can create a graph with exactly the required size. In production code, every allocation must be checked and every allocated block must eventually be released.
Allocating And Initialising The Matrix
The following function creates a graph and sets all entries to zero:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int vertices;
int **matrix;
} Graph;
Graph *create_graph(int vertices) {
Graph *graph = malloc(sizeof(Graph));
if (graph == NULL) {
return NULL;
}
graph->vertices = vertices;
graph->matrix = malloc(vertices * sizeof(int *));
if (graph->matrix == NULL) {
free(graph);
return NULL;
}
for (int i = 0; i < vertices; i++) {
graph->matrix[i] = calloc(vertices, sizeof(int));
if (graph->matrix[i] == NULL) {
for (int j = 0; j < i; j++) {
free(graph->matrix[j]);
}
free(graph->matrix);
free(graph);
return NULL;
}
}
return graph;
}
calloc is useful here because it allocates memory and fills it with zero bytes. Consequently, every possible edge initially has the value 0. A successful call returns a graph whose vertices are numbered from 0 through vertices - 1.
A cleanup function prevents memory leaks:
void destroy_graph(Graph *graph) {
if (graph == NULL) {
return;
}
for (int i = 0; i < graph->vertices; i++) {
free(graph->matrix[i]);
}
free(graph->matrix);
free(graph);
}
The allocation failure path matters in C. If the fourth row cannot be allocated, the first three rows must be freed before returning. This kind of careful resource handling is important in long-running services used by organisations in Sydney or Melbourne, where a small leak can accumulate across many requests.
Adding Removing And Inspecting Edges
An edge insertion function can support either directed or undirected behaviour:
int add_edge(Graph *graph, int source, int destination, int directed) {
if (graph == NULL ||
source < 0 || source >= graph->vertices ||
destination < 0 || destination >= graph->vertices) {
return 0;
}
graph->matrix[source][destination] = 1;
if (!directed) {
graph->matrix[destination][source] = 1;
}
return 1;
}
The boundary checks prevent invalid array access. Passing a vertex such as -1 or vertices would otherwise cause undefined behaviour. Returning 1 for success and 0 for failure gives the caller a simple way to validate input.
Removing an edge follows the same pattern:
int remove_edge(Graph *graph, int source, int destination, int directed) {
if (graph == NULL ||
source < 0 || source >= graph->vertices ||
destination < 0 || destination >= graph->vertices) {
return 0;
}
graph->matrix[source][destination] = 0;
if (!directed) {
graph->matrix[destination][source] = 0;
}
return 1;
}
int has_edge(const Graph *graph, int source, int destination) {
if (graph == NULL ||
source < 0 || source >= graph->vertices ||
destination < 0 || destination >= graph->vertices) {
return 0;
}
return graph->matrix[source][destination] != 0;
}
For an undirected graph, the caller should use the same directed choice consistently. Mixing directed and undirected updates can produce a matrix that no longer reflects the intended model.
Supporting Weights And Self-Loops
A binary matrix is appropriate for an unweighted graph, but a weighted graph can store costs directly. For example, a road graph might use travel distance in kilometres, while a public transport graph could store average travel time between stations in minutes. A special value such as -1 can represent “no edge”.
#define NO_EDGE -1
int weighted_matrix[4][4] = {
{0, 12, NO_EDGE, 7},
{12, 0, 4, NO_EDGE},
{NO_EDGE, 4, 0, 9},
{7, NO_EDGE, 9, 0}
};
The diagonal usually contains zero because travelling from a vertex to itself costs nothing. A self-loop is an exception: if the application permits a connection from a vertex back to itself, its diagonal value can hold that edge’s weight.
A weighted matrix should use a type suitable for the values involved. int is adequate for small distances, but long, float, or double may be necessary for larger costs or fractional measurements. Algorithms such as Dijkstra’s shortest-path method also need a carefully chosen “infinity” value that cannot be confused with a valid edge weight.
Traversing The Stored Graph
Checking an edge in an adjacency matrix takes constant time, O(1), because the program directly indexes one cell. Inserting and removing an edge also take O(1). These are the main strengths of the representation.
Finding every neighbour of one vertex takes O(V), since the program must scan an entire row. A breadth-first search or depth-first search implemented with a matrix takes O(V²): for each visited vertex, the algorithm may inspect all columns. The matrix itself requires O(V²) memory.
A simple depth-first search can be written like this:
void depth_first_search(const Graph *graph, int vertex, int *visited) {
visited[vertex] = 1;
printf("%d ", vertex);
for (int next = 0; next < graph->vertices; next++) {
if (graph->matrix[vertex][next] && !visited[next]) {
depth_first_search(graph, next, visited);
}
}
}
The visited array prevents repeated visits and stops recursion from continuing around a cycle. For a large graph, an iterative version using an explicit stack may avoid exhausting the call stack. The same matrix can support connectivity checks, cycle detection, and reachability analysis.
Testing Common Graph Cases
A useful test program should cover more than a triangle of connected vertices. Test an empty graph, a graph with one vertex, a graph containing isolated vertices, and a graph with several disconnected components. These cases reveal incorrect assumptions about diagonals and neighbour scanning.
Directed graphs deserve separate tests because matrix[a][b] may be 1 while matrix[b][a] remains 0. For an undirected graph, verify symmetry after every insertion and removal. Also test invalid vertex numbers to ensure the functions reject them without accessing memory outside the matrix.
A small driver could look like this:
int main(void) {
Graph *graph = create_graph(5);
if (graph == NULL) {
return EXIT_FAILURE;
}
add_edge(graph, 0, 1, 0);
add_edge(graph, 0, 3, 0);
add_edge(graph, 1, 4, 0);
int visited[5] = {0};
depth_first_search(graph, 0, visited);
printf("\n");
destroy_graph(graph);
return EXIT_SUCCESS;
}
Compile with warnings enabled:
gcc -Wall -Wextra -std=c11 graph.c -o graph
Warnings often identify missing declarations, suspicious conversions, and unused variables before they become runtime faults. When graph data comes from real Australian customers or transport users, privacy obligations under the Privacy Act 1988 and its Australian Privacy Principles should also be considered. A relationship matrix can expose sensitive information even when its entries contain only zeros and ones.
Practical Implementation Habits
Clear conventions make graph code easier to maintain. Decide whether vertices use zero-based or one-based labels, document whether the graph is directed, and define what a zero or sentinel value means. In a Brisbane route planner, for instance, a missing road connection must not be confused with a road whose measured cost is genuinely zero.
When importing data, validate the vertex count, reject malformed edge pairs, and avoid trusting input from files or network requests. Australian applications may receive data from different state systems with inconsistent suburb names or station identifiers, so mapping external labels to compact integer indices is often useful. For algorithm practice, distinguish graph traversal from ordering problems; a review of binary search for LIS illustrates why a specialised data structure can be preferable to a general graph.
Useful habits for a reliable implementation include:
- Check every
malloc,calloc, and input operation before using its result. - Keep edge insertion and removal in dedicated functions.
- Use constants such as
NO_EDGEinstead of unexplained numeric literals. - Test symmetry for undirected graphs and directionality for directed graphs.
- Compile with
-Wall -Wextraand use sanitising tools during development. - Free every matrix row, the row-pointer array, and the graph structure.
- Choose an adjacency list when the graph is sparse or its vertex count is large.