Course contentsShow
← C
Lesson 1043 of 1,21914. Data Structures in CFree lesson

Adding edges in undirected graphs

Adding edges in undirected graphs

What you'll learn: How to create a two-way connection between two nodes in an adjacency matrix.

The Two-Way Street

In an undirected graph, an "edge" represents a relationship that works both ways. If person A is friends with person B, then person B is automatically friends with person A.

Think of an adjacency matrix like a seating chart for a wedding. If you want to record that "Table 1" and "Table 4" are connected, you can't just mark it in one spot. To make the relationship truly undirected, you must mark the connection at the intersection of (Row 1, Column 4) and at (Row 4, Column 1). This symmetry is what makes the graph undirected.

Coding the Connection

When using a 2D array (matrix) to represent our graph, an edge is usually represented by the number 1 (connected) or 0 (not connected).

To add an edge, we take the two vertex numbers as inputs and update two different cells in our array. If we only updated one cell, we would accidentally create a "directed" graph (a one-way street), which is a different data structure entirely.

#include <stdio.h>

#define V 5 // A graph with 5 vertices (0 to 4)

void addEdge(int matrix[V][V], int start, int end) {
    // Mark the connection from start to end
    matrix[start][end] = 1;
    
    // Because it is undirected, mark the connection from end to start
    matrix[end][start] = 1;
}

int main() {
    int adjMatrix[V][V] = {0}; // Initialize all to 0 (no edges)

    // Add an edge between vertex 0 and vertex 3
    addEdge(adjMatrix, 0, 3);

    // Now adjMatrix[0][3] is 1 AND adjMatrix[3][0] is 1
    printf("Connection 0 to 3: %d\n", adjMatrix[0][3]);
    printf("Connection 3 to 0: %d\n", adjMatrix[3][0]);

    return 0;
}

Symmetry is Key

When you look at a completed adjacency matrix for an undirected graph, you will notice a perfect mirror image across the diagonal (from top-left to bottom-right). This is because every matrix[i][j] must equal matrix[j][i]. If you ever find a 1 at [2][4] but a 0 at [4][2], your undirected graph is broken! Always remember: in an undirected world, every bridge you build must allow traffic in both directions.

Key takeaway

To add an edge in an undirected adjacency matrix, you must set two values—matrix[a][b] and matrix[b][a]—to 1.