In this blog post, weโll dive into implementing and working with a Directed Graph using Python. We'll also walk through basic components such as edges, adjacency lists, and traversal.
A Directed Graph (or Digraph) is a set of nodes connected by edges, where the edges have a direction - meaning they go from one node to another.
Source: Wikipedia โ Directed Graph
๐ ๏ธ Here's how you can build a simple directed graph class in Python using an adjacency list:
class Graph:
def __init__(self, vno):
self.vertex_count = vno
self.adj_list = {v: [] for v in range(vno)}
def add_edge(self, u, v, weight=1):
if 0 <= u < self.vertex_count and 0 <= v < self.vertex_count:
self.adj_list[u].append((v, weight))
def print_graph(self):
for vertex, neighbor in self.adj_list.items():
print(f'Vertex {vertex} : {neighbor}')
๐ In the above code:
add_edge(u, v)
adds a directed edge from node u to node
v.
๐งช Let's test it with a few nodes and connections:
if __name__ == "__main__":
graph = Graph(4)
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(2, 3)
graph.print_graph()
โ Expected Output:
Vertex 0 : [(1, 1), (2, 1)]
Vertex 1 : []
Vertex 2 : [(3, 1)]
Vertex 3 : []
๐ฏ Key Takeaways:
(u -> v)
.v -> u
is assumed unless explicitly added.๐ Source Code: GitHub Repository
Founding Engineer
Ally Solutions