(l)
| 1 | # Finding longest distance in Directed Acyclic Graph using KahnsAlgorithm |
| 2 | def longestDistance(l): |
| 3 | indegree = [0] * len(l) |
| 4 | queue = [] |
| 5 | longDist = [1] * len(l) |
| 6 | |
| 7 | for key, values in l.items(): |
| 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 l[vertex]: |
| 18 | indegree[x] -= 1 |
| 19 | |
| 20 | if longDist[vertex] + 1 > longDist[x]: |
| 21 | longDist[x] = longDist[vertex] + 1 |
| 22 | |
| 23 | if indegree[x] == 0: |
| 24 | queue.append(x) |
| 25 | |
| 26 | print(max(longDist)) |
| 27 | |
| 28 | # Adjacency list of Graph |
| 29 | l = {0:[2,3,4], 1:[2,7], 2:[5], 3:[5,7], 4:[7], 5:[6], 6:[7], 7:[]} |
no test coverage detected