VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-if-there-is-a-path-between-two-vertices-in-a-given-graph/

⇱ Find if there is a path between two vertices in a directed graph - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find if there is a path between two vertices in a directed graph

Last Updated : 14 May, 2025

Given a Directed Graph and two vertices src and dest, check whether there is a path from src to dest.

Example:

Consider the following Graph: adj[][] = [ [], [0, 2], [0, 3], [], [2] ]
👁 Lightbox
Input : src = 1, dest = 3
Output: Yes
Explanation: There is a path from 1 to 3, 1 -> 2 -> 3

Input : src = 0, dest = 3
Output: No
Explanation: There is no path from 0 to 3.

Using Depth First Search - O(V + E) time and O(V) time

The idea is to start from the source vertex and explore as far as possible along each branch before moving backFind if there is a path between two vertices in a directed graphFind if there is a path between two vertices in a directed graph. If during this traversal we encounter the destination vertex, we can conclude that there exists a path from source to destination.

Step by step approach:

  1. Mark all vertices as not visited and start DFS from source node.
  2. If current node equals destination, return true.
  3. Otherwise, mark current vertex as visited and recursively check all adjacent vertices.
    • If any recursive call returns true, return true; otherwise, return false.

Output
Yes

Using Breadth First Search - O(V + E) time and O(V) space

The idea is to start from the source vertex and explore all neighboring vertices at the present depth before moving on to vertices at the next level.

Step by step approach:

  1. Initialize an empty queue and push source node into it.
  2. While queue is not empty:
    • Pop the front node from queue. If node is destination node, return true.
    • Otherwise, mark and push all the unvisited adjacent nodes into the queue.
  3. If destination node is not reachable, return false.

Output
Yes
Comment
Article Tags:
Article Tags: