Weighted Adjacency Matrix for Directed Graphs
Space: O(n²)Weight Query: O(1)Weighted Matrix
⚖️Understanding Weighted Adjacency Matrices
A weighted adjacency matrix is a square matrix used to represent a weighted directed graph. For a graph with n vertices, the adjacency matrix is an n×n matrixwhere each cell [i][j] contains the weight of the edge from vertex i to vertex j, or 0 if no edge exists.
Unlike unweighted graphs that store only 0s and 1s, weighted matrices store actual edge weights, making them ideal for representing distances, costs, capacities, or any numerical relationship between vertices.
matrix[i][j] = weight if edge exists from vertex i to vertex j, 0 otherwise
💻Implementation
🔍Properties & Complexity
Time Complexity
- • Weight lookup: O(1)
- • Add weighted edge: O(1)
- • Remove edge: O(1)
- • Get neighbors with weights: O(n)
Space & Properties
- • Space: O(n²) always
- • Memory: Fixed regardless of edge count
- • Representation: Dense storage
- • Matrix ops: Easy to perform
✅ Best Use Cases
- • Weighted graphs: Roads with distances, network costs, capacities
- • Fast weight queries: Frequent "what's the weight?" checks
- • Shortest path algorithms: Dijkstra's, Floyd-Warshall implementations
- • Dense weighted graphs: When most vertex pairs have weighted edges
- • Flow networks: Max flow, min cost flow problems
⚠️ Limitations
- • Space inefficient: Wastes memory for sparse graphs
- • Fixed size: Difficult to add/remove vertices
- • Large graphs: O(n²) space becomes prohibitive
- • Iteration: O(n) to find all neighbors
- • Cache performance: Poor for very large matrices