You are given a directed acyclic graph with the nodes . Your task is to count how many different paths there are in the graph.
A path is a sequence of nodes with a forward directional edge between all pairs of adjacent nodes. A single node counts as a path too.
In a file allpaths.py
, implement the class AllPaths
with the following methods:
add_edge
adds an edge between two nodescount
returns the number of different paths
Implement the method count
efficiently using dynamic programming.
class AllPaths: def __init__(self, n): # TODO def add_edge(self, a, b): # TODO def count(self): # TODO if __name__ == "__main__": counter = AllPaths(4) counter.add_edge(1, 2) counter.add_edge(1, 3) counter.add_edge(2, 4) counter.add_edge(3, 4) print(counter.count()) # 10 counter.add_edge(2, 3) print(counter.count()) # 14
The first call to the method count
includes the following paths into the count: