Given a Directed Graph and two vertices in it, check whether there is a path from the first given vertex to second. For example, in the following graph, there is a path from vertex 1 to 3. As another example, there is no path from 3 to 0.

We can either use Breadth First Search (BFS) or Depth First Search (DFS) to find path between two vertices. Take the first vertex as source in BFS (or DFS), follow the standard BFS (or DFS). If we see the second vertex in our traversal, then return true. Else return false.

Following is Java code implementation, that use BFS for finding reachability of second vertex from first vertex.

directed-graph

Java Programming to Find if there is a path between two vertices in a directed graph:

// Java program to check if there is exist a path between two vertices
// of a graph.
import java.io.*;
import java.util.*;
import java.util.LinkedList;


class Graph
{
private int V;
private LinkedList<Integer> adj[];


Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}


void addEdge(int v,int w) { adj[v].add(w); }


Boolean isReachable(int s, int d)
{
LinkedList<Integer>temp;


boolean visited[] = new boolean[V];


LinkedList<Integer> queue = new LinkedList<Integer>();


visited[s]=true;
queue.add(s);


Iterator<Integer> i;
while (queue.size()!=0)
{

s = queue.poll();

int n;
i = adj[s].listIterator();


while (i.hasNext())
{
n = i.next();


if (n==d)
return true;


if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}


return false;
}


public static void main(String args[])
{

Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

int u = 1;
int v = 3;
if (g.isReachable(u, v))
System.out.println("There is a path from " + u +" to " + v);
else
System.out.println("There is no path from " + u +" to " + v);;

u = 3;
v = 1;
if (g.isReachable(u, v))
System.out.println("There is a path from " + u +" to " + v);
else
System.out.println("There is no path from " + u +" to " + v);;
}
}

Output:

 There is a path from 1 to 3
 There is no path from 3 to 1
[ad type=”banner”]