Adjacency Matrix for Undirected Graphs
Space: O(n²)Edge Query: O(1)Symmetric Matrix
📊Understanding Undirected Graph Adjacency Matrices
An adjacency matrix for an undirected graph is a square matrix used to represent connections between vertices. For a graph with n vertices, the adjacency matrix is an n×n symmetric matrix where each cell [i][j] indicates whether there is an edge between vertex i and vertex j.
In an undirected graph, the matrix is always symmetric because if there's an edge from vertex A to vertex B, there's also an edge from B to A.
matrix[i][j] = matrix[j][i] = 1 if edge exists between vertices i and j, 0 otherwise
💻Implementation
🔍Properties & Complexity
Time Complexity
- • Edge lookup: O(1)
- • Add edge: O(1) - updates 2 cells
- • Remove edge: O(1) - updates 2 cells
- • Get neighbors: O(n)
Space & Properties
- • Space: O(n²) always
- • Symmetry: Matrix is always symmetric
- • Diagonal: Usually 0 (no self-loops)
- • Memory efficiency: Can store only upper triangle
✅ Best Use Cases
- • Social networks: Friendship connections
- • Road networks: Bidirectional roads
- • Communication networks: Two-way connections
- • Dense graphs: When most vertices are connected
- • Matrix operations: Graph algorithms using linear algebra
🔄 Key Differences
- • Symmetric matrix: matrix[i][j] = matrix[j][i]
- • Degree concept: Number of neighbors for each vertex
- • Memory optimization: Can store only upper/lower triangle
- • Edge counting: Each edge counted once, not twice
- • No direction: Relationships are bidirectional