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

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.

 

Solution 1: DFS

public static boolean pathExistedDFS(DirectedGraph g, int src, int dest) {
	boolean[] visited = new boolean[g.V];
	return dfsUtil(g, visited, src, dest);
}

private static boolean dfsUtil(DirectedGraph g, boolean[] visited, int src, int dest) {
	if(src == dest) return true;
	visited[src] = true;
	for(int u : g.adj[src]) {
		if(!visited[u] && dfsUtil(g, visited, u, dest)) {
			return true;
		}
	}
	return false;
}

 

Solution 2: BFS

public static boolean pathExistedBFS(DirectedGraph g, int src, int dest) {
	if(src == dest) return true;
	boolean[] visited = new boolean[g.V];
	Queue<Integer> queue = new LinkedList<>();
	queue.offer(src);
	visited[src] = true;
	while(!queue.isEmpty()) {
		int v = queue.poll();
		for(int u:g.adj[v]) {
			if(u == dest) return true;
			if(!visited[u]) {
				visited[u] = true;
				queue.offer(u);
			}
		}
	}
	return false;
}

public static void main(String[] args) {
	DirectedGraph g = new DirectedGraph(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 = 0, v = 2;
	if(pathExistedBFS(g, u, v)) {
		System.out.println("path exists from " + u + " to " + v);
	} else {
		System.out.println("path does not exist from " + u + " to " + v);
	}
}

Reference:

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

猜你喜欢

转载自yuanhsh.iteye.com/blog/2207956