0

I have a general question regarding how to find shortest path and longest path in an undirected graph with simple edges where edges have no weights.

Is it a correct conclusion that we need to use DFS algorithm to find the longest path in a graph, while we need to use BFS algorithm to find shortest path in a graph.

I understand that when we use BFS we visit the nodes layer by layer, and we can use it for shortest path finding (that is probably why Dijkstra is BFS-based or similar to BFS). But i do not see how efficiently we can find the longest path from using BFS. Can somebody elaborate?

Also, I understand that using DFS to find the longest path might not efficient and we may need to use Dynamic programming idea to enhance the time complexity, but lets ignore it for the sake of functionality for this discussion.

Ashkanxy
  • 2,380
  • 2
  • 6
  • 17
  • If an undirected graph is acyclic, then each connected part is a tree, and finding the longest path is easy by DFS or BFS. If an undirected graph has cycles, then there is no longest path, because you can go around a cycle again and again ad infinitum. If instead you want to find the longest shortest path to any vertex, then you can use BFS. If you want to find the longest *simple* path, then that problem is NP-hard, like finding a Hamiltonian cycle. – Matt Timmermans Mar 26 '21 at 05:01
  • @MattTimmermans Thanks for your comment, i think if there is a cycle in a graph we can still find the longest path, by keeping track of visited nodes, in a way that if a node is already visited, we should not visit it for the second time. Also i came up with my conclusion by reviewing the following article https://www.geeksforgeeks.org/longest-path-in-a-directed-acyclic-graph-dynamic-programming/ – Ashkanxy Mar 26 '21 at 06:27
  • @Ashkanxy The graph in your link is a directed acyclic graph. Just goes to show you how changing one or two constraints on a problem can have a drastic effect on how easy (or hard) it is to solve. – beaker Mar 29 '21 at 00:11
  • 1
    @Ash Were the answers helpful? Let us know if you need any more or different inputs. – Shridhar R Kulkarni Jun 11 '21 at 03:45

1 Answers1

7

Made this for you. Hope you find it easier now.

enter image description here

Shridhar R Kulkarni
  • 6,653
  • 3
  • 37
  • 57