Longest Path in Undirected Acyclic Graph
Last updated
Last updated
Given an undirected acyclic Graph (also known as a forest, or a connected component of trees). Find the length of the longest path between between any two nodes.
The Idea: The brute force method would iterate every node in the graph, and find the maximum distance relative to that node. This would run in O(|V|^2) time. Lets think about this another way. We know that the length of the longest distance has to be between two nodes that are the greatest distance apart (in terms of number of edges). If we can find one just one of these nodes, then we know how to find the other node by by initiating a BFS from that node. This is because this node is on the 'edge' of either end of the graph, and so initiating a BFS (or DFS) would branch out to the further complementing side. So now the problem has deduced to finding one the these 'edge' nodes. To find this node, we can BFS from any part of the graph and find the node that carries the maximum distance from that node.
Complexity: O(|V|) time and space