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

9 篇文章 0 订阅
6 篇文章 0 订阅

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值