C Adjacency Matrix

Intermediate
6 min read
Updated: Nov 2026
1 example

A Grid of Connections

An adjacency matrix is a V x V array where m[u][v] is 1 (or the weight) if an edge exists. Checking for an edge is O(1); listing neighbors takes O(V); memory is O(V^2). It suits dense graphs and small vertex counts.

Remember
int m[V][V] = {0};
m[u][v] = m[v][u] = 1;       /* add undirected edge */
if (m[u][v]) ...             /* O(1) edge test      */

Cheat Sheet

Keep these facts handy while you work with Adjacency Matrix in C.

TopicDetail
Edge testO(1)
NeighborsO(V) row scan
MemoryO(V^2)
Best forDense graphs

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Adjacency List.

Example 1 — Build and print a matrix

Four vertices and four edges.

C
#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

  1. Each edge sets two symmetric cells.
  2. Row 2 has ones at columns 0, 1, and 3.
  3. Scanning a row lists a vertex's neighbors.

Edge Cases & Pitfalls

Check these before relying on Adjacency Matrix in real programs.

sparse

Wasted memory

A graph with 10,000 vertices needs 100 million cells.

diag

Self loops on the diagonal

Decide whether m[v][v] is allowed.

Key Takeaways

  • Fast edge lookup.
  • O(V^2) memory.
  • Good for dense graphs.

One line: An adjacency matrix is a V x V array where m[u][v] is 1 (or the weight) if an edge exists.

Frequently Asked Questions

A square 2D array where entry (u, v) indicates whether an edge from u to v exists (or its weight).
When the graph is dense or you need constant-time edge existence checks.
Continue with "C Adjacency List" next. Store only existing edges using an array of linked lists. The C Graphs hub lists every topic in order.

Next: Adjacency List

Store only existing edges using an array of linked lists.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful