Longest Path in Undirected Acyclic Graph
import collections
import queue
def longest_path(edges):
if not edges:
return 0
g = collections.defaultdict(list)
for u, v in edges:
g[u].append(v)
g[v].append(u)
def BFS(start):
visited = set()
maxx_dist = -1
maxx_node = -1
q = queue.Queue()
q.put((start, 0))
while not q.empty():
node, dist = q.get()
visited.add(node)
if dist > maxx_dist:
maxx_dist, maxx_node = dist, node
for edge in g[node]:
if edge not in visited:
q.put((edge, dist + 1))
return maxx_node, maxx_dist
max_node1, dist_max1 = BFS(edges[0][0])
abs_max, abs_dist = BFS(max_node1)
return abs_dist
edges = [[1,2], [2,3], [3,4], [4,6], [6,5], [4,8], [8,7], [7,10], [8, 11], [8,9], [9, 12]]
print(longest_path(edges))Last updated
