An undirected graph is a specific type of directed graph, where for each edge (a, b) there also exists (b, a).
Thus, you can implement it by saving edges twice (normal and inverse), but it is better to write a class so that it is consistent:
from collections import defaultdict class UndirectedGraph: def __init__(self): self.edge = defaultdict(set) def add_edge(self, a, b): self.edge[a].add(b) self.edge[b].add(a) def remove_edge(self, a, b): self.edge[a].remove(b) self.edge[b].remove(a) def has_edge(self, a, b): return b in self.edge[a] or a in self.edge[b] def neighbours(self, a): return set(self.edge[a])
It is very simple, and depending on the operations you want to do, you may remove some method, or you may need to add others.
>>> g=UndirectedGraph() >>> g.add_edge('a','b') >>> g.add_edge('a','c') >>> g.add_edge('c','d') >>> g.add_edge('a','d') >>> g.remove_edge('a','d') >>> g.has_edge('a','d') False >>> g.has_edge('a','c') True >>> g.neighbours('c') {'a', 'd'}
source share