Find if there is a path between two vertices in a directed graph - GeeksforGeeks
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.
BFS:
Read full article from Find if there is a path between two vertices in a directed graph - GeeksforGeeks
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.
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 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;
- }
Read full article from Find if there is a path between two vertices in a directed graph - GeeksforGeeks