![]() |
| Directed Graph |
BFS Algorithm:
- The implementation below is using BFS.
- Create a queue and a visited array initially filled with 0, of size V where V is a number of vertices.
- Insert the starting node in the queue, i.e. push u in the queue and mark u as visited.
- Run a loop until the queue is not empty.
- Dequeue the front element of the queue. Iterate all its adjacent elements. If any of the adjacent elements is the destination return true. Push all the adjacent and unvisited vertices in the queue and mark them as visited.
- Return false as the destination is not reached in BFS.
Output There is a path from 1 to 3
There is no path from 3 to 1
There is a path from 1 to 3 There is no path from 3 to 1
Complexity Analysis:
- Time Complexity: O(V+E) where V is number of vertices in the graph and E is number of edges in the graph.
- Space Complexity: O(V).
There can be atmost V elements in the queue. So the space needed is O(V).
DFS Algorithm:
- if start==end return 1 since we have to reached our destination.
- Mark start as visited.
- Traverse directly connected vertices of start and recur the function dfs for every such unexplored vertex.
- return 0 if we do not reach our destination.
Complexity Analysis:
Time Complexity: O(V+E) where V is number of vertices in the graph and E is number of edges in the graph.
Space Complexity: O(V).
There can be atmost V elements in the stack. So the space needed is O(V).
Trade-offs between BFS and DFS:
Breadth-First search can be useful to find the shortest path between nodes, and depth-first search may traverse one adjacent node very deeply before ever going into immediate neighbours.

0 Comments