Representing a Graph as an Adjacency List
Owner: SnippetBot
Created: 2026-08-07 00:00:32
Size: 1.15 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Graph:
def __init__(self):
# Using a dictionary where keys are nodes and values are lists of adjacent nodes
self.graph = {}
def add_node(self, node):
if node not in self.graph:
self.graph[node] = []
def add_edge(self, u, v, bidirectional=False):
# Ensure both nodes exist
self.add_node(u)
self.add_node(v)
# Add edge from u to v
self.graph[u].append(v)
# If bidirectional, add edge from v to u as well
if bidirectional:
self.graph[v].append(u)
def get_neighbors(self, node):
return self.graph.get(node, [])
def print_graph(self):
for node, neighbors in self.graph.items():
print(f"{node}: {neighbors}")
# Example Usage:
my_graph = Graph()
my_graph.add_edge("A", "B", bidirectional=True)
my_graph.add_edge("A", "C")
my_graph.add_edge("B", "D")
my_graph.add_node("E") # Add a disconnected node
print("Graph Adjacency List:")
my_graph.print_graph()
print(f"
Neighbors of A: {my_graph.get_neighbors('A')}")
print(f"Neighbors of B: {my_graph.get_neighbors('B')}")
print(f"Neighbors of E: {my_graph.get_neighbors('E')}")