(graph)
| 1 | # Finding longest distance in Directed Acyclic Graph using KahnsAlgorithm |
| 2 | def longest_distance(graph): |
| 3 | indegree = [0] * len(graph) |
| 4 | queue = [] |
| 5 | long_dist = [1] * len(graph) |
| 6 | |
| 7 | for values in graph.values(): |
| 8 | for i in values: |
| 9 | indegree[i] += 1 |
| 10 | |
| 11 | for i in range(len(indegree)): |
| 12 | if indegree[i] == 0: |
| 13 | queue.append(i) |
| 14 | |
| 15 | while queue: |
| 16 | vertex = queue.pop(0) |
| 17 | for x in graph[vertex]: |
| 18 | indegree[x] -= 1 |
| 19 | |
| 20 | long_dist[x] = max(long_dist[x], long_dist[vertex] + 1) |
| 21 | |
| 22 | if indegree[x] == 0: |
| 23 | queue.append(x) |
| 24 | |
| 25 | print(max(long_dist)) |
| 26 | |
| 27 | |
| 28 | # Adjacency list of Graph |
no test coverage detected