graph

Graph class
mail@pastecode.io avatar
unknown
python
a month ago
649 B
0
Indexable
Never
# Adjacency list, unweighted and undirected.
class Graph:
    def __init__(self):
        self.graph = {}

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

    def add_edge(self, vertex1, vertex2):
        if vertex1 in self.graph and vertex2 in self.graph:
            self.graph[vertex1].append(vertex2)
            self.graph[vertex2].append(vertex1)
        else:
            print("One or both vertices not found in graph.")

    def show_edges(self):
        for vertex in self.graph:
            for neighbour in self.graph[vertex]:
                print(f"*{vertex}, {neighbour})")
Leave a Comment