1. Understand the Goal: The user wants an implementation of a graph using an adjacency matrix.
-
Identify the Core Concepts:
- Graph: A set of vertices (nodes) connected by edges.
- Adjacency Matrix: A 2D array (square matrix) where rows and columns represent vertices. M[i][j]=1 (or weight) if there is an edge from vertex i to vertex j, and 0 otherwise.
- Properties to consider: Directed vs. Undirected, Weighted vs. Unweighted.
-
Choose a Programming Language: Python is the most common language for these types of general algorithm requests because it's readable and pseudo-code-like. I should probably provide a Python implementation, maybe a C++ or Java one if I feel it adds value, but Python is usually the safest bet for a primary answer.
-
Design the Class Structure:
__init__: Needs to know the number of vertices.
add_edge: Method to connect two vertices. Need to handle weights (optional but good practice).
remove_edge: Method to disconnect vertices.
print_matrix: Utility to visualize the graph.
-
Drafting the Implementation (Mental or Scratchpad):
-
Unweighted Graph:
Matrix is V×V.
matrix[u][v] = 1
If undirected: matrix[v][u] = 1 as well.
-
Weighted Graph:
Usually initialized with 0 (or infinity).
matrix[u][v] = weight
If undirected: matrix[v][u] = weight.
-
Refining the class:
Let's make it flexible. I'll create a Python class that handles both directed/undirected and weighted/unweighted, or just keep it simple. Simple is better for a basic request.
-
Approach: I will provide a standard implementation that assumes an unweighted graph (where 1 represents an edge) but mention how to adapt it for weights.
-
Step-by-Step Implementation Plan (Python):
- Class
Graph:
- Attributes:
num_vertices, matrix (a list of lists).
- Method
add_edge(u, v):
- Set
matrix[u][v] = 1.
- (Optional: handle directed vs undirected. I'll assume undirected for the simplest "Graph" interpretation, but maybe make it an option in the constructor). Self-correction: Adjacency matrices are often demonstrated with directed graphs to show asymmetry, but undirected is simpler for beginners. Let's stick to a generic one, maybe undirected as default but easy to change. actually, let's just make a Directed/Undirected flag.
- Method
remove_edge(u, v): Set to 0.
- Method
__str__: Print the matrix nicely.
-
Writing the Code (Iterative refinement):
class Graph:
def __init__(self, num_vertices):
self.num_vertices = num_vertices
# Initialize matrix with 0s
self.matrix = [[0] * num_vertices for _ in range(num_vertices)]
def add_edge(self, u, v, weight=1):
# Bounds checking is good practice
if u >= self.num_vertices or v >= self.num_vertices:
return
self.matrix[u][v] = weight
# If undirected, uncomment next line:
# self.matrix[v][u] = weight
Critique: Implementing a directed graph is usually the standard "math" representation, but users often want undirected. I will implement an Undirected Graph as the primary example, as it produces a symmetric matrix which is easier to verify visually. I will add a comment about directed graphs.
-
Adding Complexity (Weighted Graphs):
It's often useful to show how to handle weights. Instead of just 0/1, use 0/weight. I'll stick to 0/1 for the basic implementation to keep it clear, but mention weights in the comments.
-
Refining the Output:
The user just asked to "Implement a graph using an adjacency matrix." I should provide:
- The Code (Python is best).
- Explanation of the logic.
- Time/Space complexity analysis.
-
Final Code Structure (Python):
class Graph:
def __init__(self, size):
self.size = size
self.adj_matrix = [[0] * size for _ in range(size)]
def add_edge(self, v1, v2, weight=1):
if v1 == v2:
print(f"Same vertex {v1} and {v2}")
else:
self.adj_matrix[v1][v2] = weight
self.adj_matrix[v2][v1] = weight # For undirected
def remove_edge(self, v1, v2):
if self.adj_matrix[v1][v2] == 0:
print(f"No edge between {v1} and {v2}")
else:
self.adj_matrix[v1][v2] = 0
self.adj_matrix[v2][v1] = 0
def print_matrix(self):
for row in self.adj_matrix:
print(row)
-
Adding C++ and Java?
It is very common for this type of DSA question to require specific languages. I will provide Python as the main one, but add a C++ and/or Java example below for completeness, as memory management (pointers/vectors) makes the matrix implementation slightly more interesting in C++.
-
Reviewing Complexity:
- Space: O(V2).
- Add Edge: O(1).
- Remove Edge: O(1).
- Check if edge exists: .
-
Final Polish:
- Make the variable names clear (
v1, v2, num_vertices).
- Ensure the initialization handles the list of lists correctly (common mistake is
[[0]*n]*n which creates shallow copies). I must use [[0]*n for _ in range(n)].
-
Constructing the Final Response:
- Introduction.
- Python Implementation (Most detailed).
- Java/C++ Implementation (Secondary).
- Explanation of methods.
- Pros/Cons.
(Self-Correction during drafting Java code): In Java, a 2D array int[][] matrix = new int[size][size]; initializes with 0 automatically. Much easier than Python list comprehensions.
(Self-Correction during drafting C++ code): std::vector<std::vector<int>> matrix; resized in constructor.
-
Final Check of the Prompt: "Implement a graph using an adjacency matrix."
The response should be code-centric with enough context to understand it.
Let's go with Python as the primary, and maybe a brief C++ example since matrix manipulation is often taught in C++ context. I'll stick to Python for the main logic to ensure readability.
Plan:
- Define the Class.
__init__: Initialize with size, create 2D array of 0s.
add_edge: update indices.
remove_edge: reset indices.
print: display.
- Driver code to run it.
Wait, directed vs undirected? I will implement an Undirected Graph by default (symmetric matrix) as it's the most common "introductory" graph, but I will add a comment on how to make it directed (remove one line).
Let's refine the complexity section. Space is the main bottleneck.
Time for add and remove is O(1).
Iterating neighbors is O(V).
Okay, ready to write.
Here is an implementation of a Graph using an Adjacency Matrix in Python.
The Concept
An adjacency matrix is a 2D array (square matrix) of size V×V (where V is the number of vertices).
matrix[i][j] = 1: There is an edge from vertex i to vertex j.
matrix[i][j] = 0: There is no edge.
Python Implementation
In this example, we will implement an Undirected Graph (meaning edges go both ways).
class Graph:
def __init__(self, num_vertices):
self.num_vertices = num_vertices
# Initialize the matrix with zeros
# We create a list of lists: [[0, 0, ...], [0, 0, ...], ...]
self.adj_matrix = [[0] * num_vertices for _ in range(num_vertices)]
def add_edge(self, v1, v2):
"""
Adds an edge between vertex v1 and v2.
"""
if v1 >= self.num_vertices or v2 >= self.num_vertices:
print(f"Error: Vertex out of bounds (Valid indices: 0-{self.num_vertices-1})")
return
# Add the edge (set to 1)
self.adj_matrix[v1][v2] = 1
# For an undirected graph, we must also set the reverse direction
self.adj_matrix[v2][v1] = 1
def remove_edge(self, v1, v2):
"""
Removes an edge between vertex v1 and v2.
"""
if v1 >= self.num_vertices or v2 >= self.num_vertices:
return
# Remove the edge (set to 0)
self.adj_matrix[v1][v2] = 0
self.adj_matrix[v2][v1] = 0
def print_matrix(self):
"""
Prints the adjacency matrix nicely formatted.
"""
print(" ", end="")
for i in range(self.num_vertices):
print(f"{i} ", end="")
print()
for i in range(self.num_vertices):
print(f"{i}:", end="")
for j in range(self.num_vertices):
print(f"{self.adj_matrix[i][j]} ", end="")
print()
print("-" * 20)
# --- Usage Example ---
# 1. Create a graph with 4 vertices (0, 1, 2, 3)
g = Graph(4)
print("Initial Graph:")
g.print_matrix()
# 2. Add edges
# Connect 0 to 1
g.add_edge(0, 1)
# Connect 0 to 2
g.add_edge(0, 2)
# Connect 1 to 2
g.add_edge(1, 2)
# Connect 2 to 3
g.add_edge(2, 3)
print("Graph after adding edges:")
g.print_matrix()
# 3. Remove an edge
g.remove_edge(1, 2)
print("Graph after removing edge (1, 2):")
g.print_matrix()
Output of the Example
Initial Graph:
0 1 2 3
0:0 0 0 0
1:0 0 0 0
2:0 0 0 0
3:0 0 0 0
--------------------
Graph after adding edges:
0 1 2 3
0:0 1 1 0
1:1 0 1 0
2:1 1 0 1
3:0 0 1 0
--------------------
Graph after removing edge (1, 2):
0 1 2 3
0:0 1 1 0
1:1 0 0 0
2:1 0 0 1
3:0 0 1 0
--------------------
Complexity Analysis
-
Space Complexity: O(V2)
- Regardless of how many edges are in the graph, the matrix always requires V×V space.
- This makes it inefficient for "sparse" graphs (graphs with few edges) but efficient for "dense" graphs.
-
Time Complexity:
- Add Edge: O( (Direct access to index).
Variations
- Directed Graph: In
add_edge, remove the line self.adj_matrix[v2][v1] = 1.
- Weighted Graph: Instead of setting the index to
1, set it to the weight of the edge. If checking for existence, check if matrix[i][j] != 0.