How to Implement Adjacency Matrix in C: Simple Guide
To implement an
adjacency matrix in C, create a 2D array where each cell matrix[i][j] represents the presence (1) or absence (0) of an edge between nodes i and j. Initialize the matrix with zeros and update it to 1 where edges exist.Syntax
An adjacency matrix in C is a 2D array of integers. Each row and column represents a node in the graph. The value at matrix[i][j] is 1 if there is an edge from node i to node j, otherwise 0.
You declare it as int matrix[size][size]; where size is the number of nodes.
c
int matrix[size][size];Example
This example shows how to create a graph with 4 nodes and add edges between them using an adjacency matrix. It prints the matrix to show connections.
c
#include <stdio.h> #define SIZE 4 int main() { int matrix[SIZE][SIZE] = {0}; // Initialize all to 0 // Add edges: 0->1, 0->2, 1->2, 2->3 matrix[0][1] = 1; matrix[0][2] = 1; matrix[1][2] = 1; matrix[2][3] = 1; // Print adjacency matrix printf("Adjacency Matrix:\n"); for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } return 0; }
Output
Adjacency Matrix:
0 1 1 0
0 0 1 0
0 0 0 1
0 0 0 0
Common Pitfalls
- Forgetting to initialize the matrix to zero can cause garbage values, leading to wrong edges.
- Mixing up row and column indices will create incorrect edges.
- Not matching the matrix size to the number of nodes causes out-of-bounds errors.
c
#include <stdio.h> #define SIZE 3 int main() { int matrix[SIZE][SIZE]; // Not initialized // Wrong: adding edge with swapped indices matrix[1][0] = 1; // Edge from 1 to 0 // Printing without initialization may show garbage for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } return 0; } // Correct way: initialize with zeros and use matrix[i][j] properly.
Quick Reference
- Declare:
int matrix[size][size]; - Initialize: Set all elements to 0 before adding edges.
- Add edge:
matrix[from][to] = 1; - Check edge:
if(matrix[i][j] == 1)means edge exists.
Key Takeaways
An adjacency matrix is a 2D array where each cell shows if an edge exists between two nodes.
Always initialize the matrix with zeros to avoid incorrect edge data.
Use matrix[i][j] = 1 to add an edge from node i to node j.
Be careful with indices to correctly represent edges in the graph.
Printing the matrix helps visualize the graph connections clearly.