forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkahns_algorithm_long.py
30 lines (22 loc) · 772 Bytes
/
kahns_algorithm_long.py
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
# Finding longest distance in Directed Acyclic Graph using KahnsAlgorithm
deflongest_distance(graph):
indegree= [0] *len(graph)
queue= []
long_dist= [1] *len(graph)
forvaluesingraph.values():
foriinvalues:
indegree[i] +=1
foriinrange(len(indegree)):
ifindegree[i] ==0:
queue.append(i)
whilequeue:
vertex=queue.pop(0)
forxingraph[vertex]:
indegree[x] -=1
long_dist[x] =max(long_dist[x], long_dist[vertex] +1)
ifindegree[x] ==0:
queue.append(x)
print(max(long_dist))
# Adjacency list of Graph
graph= {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []}
longest_distance(graph)