Given an undirected graph with N vertices and E edges and two vertices (U, V) from the graph, the task is to detect if a path exists between these two vertices. Print “Yes” if a path exists and “No” otherwise.
U = 1, V = 2
There is no edge between the two points and hence its not possible to reach 2 from 1.
U = 1, V = 3
Explanation: Vertex 3 from vertex 1 via vertices 2 or 4.
The idea is to use Floyd Warshall Algorithm. To solve the problem, we cneed to try out all intermediate vertices ranging [1, N] and check:
- If there is a direct edge already which exists between the two nodes.
- Or we have a path from node i to intermediate node k and from node k to node j.
Below is the implementation of the above approach:
Time Complexity: O(V3)
Auxiliary Space : O(V2)
There is a path from 1 to 3
Time Complexity: O(V + E)
Auxiliary Space: O(V)
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Find if there is a path between two vertices in a directed graph
- Convert the undirected graph into directed graph such that there is no path of length greater than 1
- Eulerian Path in undirected graph
- Eulerian path and circuit for undirected graph
- Find K vertices in the graph which are connected to at least one of remaining vertices
- Maximum cost path in an Undirected Graph such that no edge is visited twice in a row
- Building an undirected graph and finding shortest path using Dictionaries in Python
- Find k-cores of an undirected graph
- Maximize the number of uncolored vertices appearing along the path from root vertex and the colored vertices
- Find if an undirected graph contains an independent set of a given size
- Find all cliques of size K in an undirected graph
- Program to find Circuit Rank of an Undirected Graph
- Find two disjoint good sets of vertices in a given graph
- Find minimum weight cycle in an undirected graph
- Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
- Convert undirected connected graph to strongly connected directed graph
- Clone an Undirected Graph
- Longest path in an undirected tree
- Longest path between any pair of vertices
- Finding in and out degrees of all vertices in a graph
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.