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)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find if there is a path between two vertices in a directed graph
- Find if there is a path between two vertices in a directed graph | Set 2
- Minimize cost to color all the vertices of an Undirected Graph
- Convert the undirected graph into directed graph such that there is no path of length greater than 1
- Minimize cost to color all the vertices of an Undirected Graph using given operation
- Queries to check if vertices X and Y are in the same Connected Component of an Undirected Graph
- 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 all cliques of size K in an undirected graph
- Find if an undirected graph contains an independent set of a given size
- Find any simple cycle in an undirected unweighted Graph
- Find minimum weight cycle in an undirected graph
- Program to find Circuit Rank of an Undirected Graph
- Find two disjoint good sets of vertices in a given graph
- Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected 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.