MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / longest_distance

Function longest_distance

graphs/kahns_algorithm_long.py:2–25  ·  view source on GitHub ↗
(graph)

Source from the content-addressed store, hash-verified

1# Finding longest distance in Directed Acyclic Graph using KahnsAlgorithm
2def 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

Callers 1

Calls 2

appendMethod · 0.45
popMethod · 0.45

Tested by

no test coverage detected