How to Implement a Graph in Python Using an Adjacency List?

80 views

How to Implement a Graph in Python Using an Adjacency List?

How to Implement a Graph in Python Using an Adjacency List?

How can you represent a graph using an adjacency list in Python?

solveurit24@gmail.com Changed status to publish February 20, 2025
0

An adjacency list is a list of lists where each sublist represents the neighbors of a vertex. Here’s an example:

class Graph:
    def __init__(self):
        self.adjacency_list = {}

    def add_vertex(self, vertex):
        if vertex not in self.adjacency_list:
            self.adjacency_list[vertex] = []

    def add_edge(self, start, end):
        if start in self.adjacency_list:
            self.adjacency_list[start].append(end)
        else:
            self.add_vertex(start)
            self.adjacency_list[start].append(end)

    def print_graph(self):
        for vertex in self.adjacency_list:
            print(f"{vertex} -> {self.adjacency_list[vertex]}")

graph = Graph()
graph.add_vertex("A")
graph.add_vertex("B")
graph.add_vertex("C")
graph.add_edge("A", "B")
graph.add_edge("A", "C")
graph.add_edge("B", "A")
graph.print_graph()

solveurit24@gmail.com Changed status to publish February 20, 2025
0
You are viewing 1 out of 1 answers, click here to view all answers.