class Graph: def init(self, vertices): """Initialize the graph with the given number of vertices.""" self.V = vertices self.adjlist = [[] for _ in range(vertices)] # Create an empty adjacency list for each vertex
def add_edge(self, v, w):
"""Add an edge between vertex v and vertex w."""
self.adjlist[v].append(w) # Add w to v's list
self.adjlist[w].append(v) # Add v to w's list (for undirected graph)
def display_graph(self):
"""Display the adjacency list of the graph."""
for v in range(self.V):
print(f"{v} is connected to: {', '.join(map(str, self.adjlist[v]))}")
if name == "main": # Create a graph with 3 vertices graph = Graph(3)
# Add edges
graph.add_edge(0, 1)
graph.add_edge(1, 2)
# Display the graph
print("Graph structure:")
graph.display_graph()