Find if there is a path between two vertices in an undirected graph

• Difficulty Level : Medium
• Last Updated : 02 Dec, 2021

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.

Examples: U = 1, V = 2
Output: No
Explanation:
There is no edge between the two points and hence its not possible to reach 2 from 1.

Input: U = 1, V = 3
Output: Yes
Explanation: Vertex 3 from vertex 1 via vertices 2 or 4.

Naive Approach:
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:

1. If there is a direct edge already which exists between the two nodes.
2. 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:

Java

 // Java program to detect if a path// exists between any two vertices// for the given undirected graphimport java.util.Arrays; class GFG{ // Class representing a undirected// graph using matrix representationstatic class Graph{    int V;    int[][] g;     public Graph(int V)    {        this.V = V;                 // Rows may not be contiguous        g = new int[V + 1][V + 1];        for(int i = 0; i < V + 1; i++)        {                         // Initialize all entries            // as false to indicate            // that there are            // no edges initially            Arrays.fill(g[i], 0);        }         // Initializing node to itself        // as it is always reachable        for(int i = 1; i <= V; i++)            g[i][i] = 1;    }         // Function to add edge between nodes    void addEdge(int v, int w)    {        g[v][w] = 1;        g[w][v] = 1;    }     // Function to check if nodes are reachable    boolean isReachable(int s, int d)    {        if (g[s][d] == 1)            return true;        else            return false;    }         // Function to compute the path    void computePaths()    {                 // Use Floyd Warshall algorithm        // to detect if a path exists        for(int k = 1; k <= V; k++)        {                         // Try every vertex as an            // intermediate vertex            // to check if a path exists            for(int i = 1; i <= V; i++)            {                for(int j = 1; j <= V; j++)                    g[i][j] = g[i][j] | ((g[i][k] != 0 &&                              g[k][j] != 0) ? 1 : 0);            }        }    }}; // Driver codepublic static void main(String[] args){    Graph _g = new Graph(4);    _g.addEdge(1, 2);    _g.addEdge(2, 3);    _g.addEdge(1, 4);    _g.computePaths();     int u = 4, v = 3;    if (_g.isReachable(u, v))        System.out.println("Yes");    else        System.out.println("No");}} // This code is contributed by sanjeev2552

Python3

 # Python3 program to detect if a path# exists between any two vertices# for the given undirected graph # Class representing a undirected# graph using matrix# representationclass Graph:         def __init__(self, V):                 self.V = V                 # Initialize all entries        # as false to indicate        # that there are        # no edges initially        self.g = [[0 for j in range(self.V + 1)]                     for i in range(self.V + 1)]             # Initializing node to itself        # as it is always reachable        for i in range(self.V + 1):            self.g[i][i] = 1     # Function to add edge between nodes    def addEdge(self, v, w):         self.g[v][w] = 1        self.g[w][v] = 1     # Function to compute the path    def computePaths(self):         # Use Floyd Warshall algorithm        # to detect if a path exists        for k in range(1, self.V + 1):             # Try every vertex as an            # intermediate vertex            # to check if a path exists            for i in range(1, self.V + 1):                for j in range(1, self.V + 1):                    self.g[i][j] = (self.g[i][j] |                                   (self.g[i][k] and                                    self.g[k][j]))                         # Function to check if nodes    # are reachable    def isReachable(self, s, d):         if (self.g[s][d] == 1):            return True        else:            return False           # Driver codeif __name__=='__main__':     _g = Graph(4)    _g.addEdge(1, 2)    _g.addEdge(2, 3)    _g.addEdge(1, 4)    _g.computePaths()     u = 4    v = 3         if (_g.isReachable(u, v)):        print('Yes')    else:        print('No')         # This code is contributed by rutvik_56

C#

 // C# program to detect if a path// exists between any two vertices// for the given undirected graphusing System; public class GFG {     // Class representing a undirected    // graph using matrix representation    public         class Graph {        public             int V;        public             int[, ] g;         public Graph(int V)        {            this.V = V;             // Rows may not be contiguous            g = new int[V + 1, V + 1];            for (int i = 0; i < V + 1; i++) {                 // Initialize all entries                // as false to indicate                // that there are                // no edges initially                for (int j = 0; j < V + 1; j++)                    g[i, j] = 0;            }             // Initializing node to itself            // as it is always reachable            for (int i = 1; i <= V; i++)                g[i, i] = 1;        }         // Function to add edge between nodes        public void addEdge(int v, int w)        {            g[v, w] = 1;            g[w, v] = 1;        }         // Function to check if nodes are reachable        public bool isReachable(int s, int d)        {            if (g[s, d] == 1)                return true;            else                return false;        }         // Function to compute the path        public void computePaths()        {             // Use Floyd Warshall algorithm            // to detect if a path exists            for (int k = 1; k <= V; k++) {                 // Try every vertex as an                // intermediate vertex                // to check if a path exists                for (int i = 1; i <= V; i++) {                    for (int j = 1; j <= V; j++)                        g[i, j] = g[i, j]                                  | ((g[i, k] != 0                                      && g[k, j] != 0)                                         ? 1                                         : 0);                }            }        }    };     // Driver code    public static void Main(String[] args)    {        Graph _g = new Graph(4);        _g.addEdge(1, 2);        _g.addEdge(2, 3);        _g.addEdge(1, 4);        _g.computePaths();         int u = 4, v = 3;        if (_g.isReachable(u, v))            Console.WriteLine("Yes");        else            Console.WriteLine("No");    }} // This code is contributed by umadevi9616

Javascript


Output:
Yes

Time Complexity: O(V3
Auxiliary Space: O(V2)
Efficient Solution
We can either use BFS or DFS to find if there is a path from u to v. Below is a BFS based solution

Javascript


Output:
There is a path from 1 to 3

Time Complexity: O(V + E)
Auxiliary Space: O(V)

My Personal Notes arrow_drop_up