Skip to main content

Posts

Showing posts with the label dfs

Depth-First Search (DFS) Algorithm Explained with Examples and Applications

  What is Depth-First Search (DFS)? Depth-First Search (DFS) is a fundamental algorithm for traversing or searching tree and graph data structures. The algorithm explores as far as possible along each branch before backtracking, making it suitable for pathfinding, topological sorting, and cycle detection tasks. DFS Algorithm Explanation DFS can be implemented using either recursion (implicit call stack) or an explicit stack data structure. The core idea is: Start at the root (or any arbitrary node for a graph). Visit a node and mark it as visited. Recursively or iteratively visit all the adjacent unvisited nodes. Algorithm Steps (for Binary Tree - Recursive) Visit the current node. Recursively traverse the left subtree. Recursively traverse the right subtree. Algorithm Steps (for General Graph - Iterative with Stack) Push the start node onto the stack and mark it as visited. While the stack is not empty: Pop a node from the stack. Process the node. Push all unvisited adjacent nodes...