Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
Depth-First Search (DFS) is another fundamental
algorithm used to traverse or search through graphs and trees. Unlike Breadth-First
Search (BFS), which explores level by level, DFS dives deeper into a graph,
exploring as far down a branch as possible before backtracking. DFS can be
implemented using either a stack (iterative approach) or recursion.
DFS is particularly useful for problems where you need to
explore a graph fully, such as in scenarios involving pathfinding, cycle
detection, topological sorting, and connected components in a
graph. The algorithm starts at the root node (or any arbitrary node in the
graph), marks it as visited, and then explores each adjacent node before
backtracking.
The DFS algorithm works by:
One of the main advantages of DFS is that it can be easily
implemented using recursion, simplifying the code. It can also be
adapted to find solutions like topological sorting in Directed Acyclic
Graphs (DAGs), strongly connected components in directed graphs, and detecting
cycles in graphs.
DFS Algorithm in Java
DFS can be implemented using recursion or with an explicit
stack. Below is an example of DFS implemented using recursion:
import
java.util.*;
class
Graph {
private Map<Integer,
List<Integer>> adjacencyList = new HashMap<>();
// Add edge to the graph
public void addEdge(int v, int w) {
adjacencyList.putIfAbsent(v, new ArrayList<>());
adjacencyList.get(v).add(w);
}
// DFS Recursive method
public void DFS(int start) {
Set<Integer> visited = new HashSet<>();
DFSUtil(start, visited);
}
private void DFSUtil(int node,
Set<Integer> visited) {
// Mark the current node as visited and
print it
visited.add(node);
System.out.print(node + " ");
// Recur for all the vertices adjacent
to this node
if (adjacencyList.containsKey(node)) {
for (Integer neighbor :
adjacencyList.get(node)) {
if
(!visited.contains(neighbor)) {
DFSUtil(neighbor, visited);
}
}
}
}
}
public
class Main {
public static void main(String[] args) {
Graph graph = new Graph();
graph.addEdge(1, 2);
graph.addEdge(1, 3);
graph.addEdge(2, 4);
graph.addEdge(3, 5);
System.out.println("DFS traversal
starting from node 1:");
graph.DFS(1); // Output: 1 2 4 3 5
}
}
Time Complexity of DFS:
Space Complexity of DFS:
BFS (Breadth-First Search) explores a graph level-by-level
using a queue, which makes it ideal for finding the shortest path in unweighted
graphs or for level-order traversal. On the other hand, DFS (Depth-First
Search) dives deep into each branch before backtracking using recursion or a
stack, which is better suited for problems like cycle detection, topological
sorting, or solving mazes. BFS is more memory-intensive for wide graphs, while
DFS may hit stack limits in deep graphs.
Bellman-Ford is the preferred choice for graphs with negative edge weights because it relaxes all edges up to V-1 times and can detect negative weight cycles. Dijkstra's Algorithm assumes that once a node's shortest path is found, it won't change—which fails when a negative edge later offers a better path. Hence, Dijkstra produces incorrect results in graphs with negative weights.
No, BFS and DFS do not work correctly for weighted graphs
when computing the shortest path unless all edges have the same weight (in
which case BFS can be used). In weighted graphs, algorithms like Dijkstra or
Bellman-Ford should be used to account for varying edge weights.
Yes,
typically. Dijkstra’s Algorithm (especially with a min-priority queue) has a
time complexity of O((V + E) log V) using a binary heap, which is significantly
faster than Bellman-Ford’s O(V × E) in dense graphs.
However,
Dijkstra is restricted to graphs with non-negative weights, while Bellman-Ford
is more versatile in terms of weight handling but slower in execution.
Floyd-Warshall does not explicitly detect negative cycles but can indirectly do so. If any diagonal element dist[i][i] becomes negative, it indicates a negative weight cycle. In contrast, Bellman-Ford directly checks for cycle presence after the V-1 iterations, making it more transparent and suitable for single-source shortest path detection with cycle checking.
An adjacency matrix uses O(V²) space regardless of edge count, which is inefficient for sparse graphs. Adjacency lists use O(V + E) space, making them more space-efficient and faster for traversals in sparse graphs. Most graph algorithms like BFS, DFS, Dijkstra, and Bellman-Ford perform better with adjacency lists in large, sparse graphs.
Floyd-Warshall is preferred when the graph is dense and edge weights may be negative (but no negative cycles), as it provides a clean O(V³) solution for all-pairs shortest paths. Running Dijkstra’s Algorithm V times yields O(V × (V + E) log V), which may be better in sparse graphs but complex to implement compared to Floyd-Warshall’s simplicity.
No, by default, BFS or DFS starting from a single source
will only explore the connected component of that source. To process the entire
graph, especially for tasks like component counting or cycle detection, you
must run BFS or DFS on each unvisited node to ensure all disconnected
components are covered.
For real-time systems, efficiency and response time are critical. BFS or optimized Dijkstra (with Fibonacci or binary heaps) is ideal for fast queries in routing. Systems often precompute paths using Floyd-Warshall or store distance matrices. In large-scale applications like social networks, graph traversal is often distributed or approximated using heuristics like A*.
Most graph algorithms work for both, but implementation
varies. For DFS and BFS, directionality affects traversal order. For Dijkstra
and Bellman-Ford, directed edges must be processed correctly for accurate
pathfinding. Special attention must be paid in cycle detection, SCCs (Strongly
Connected Components), and topological sorting, which only apply to directed
graphs.
Please log in to access this content. You will be redirected to the login page shortly.
Login
Ready to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Your experience on this site will be improved by allowing cookies. Read Cookie Policy
Your experience on this site will be improved by allowing cookies. Read Cookie Policy
Comments(0)