Skip to main content

Posts

Showing posts with the label Time complexity

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...

A* Search Algorithm - Detailed Explanation with Python Example

  What is A* Search Algorithm? A* Search (pronounced "A-star") is one of the most popular and powerful pathfinding and graph traversal algorithms. It finds the shortest path between nodes using both the cost to reach a node and a heuristic estimation of the remaining cost to the goal. Key Concepts g(n):  The actual cost from the start node to the current node $n$. h(n):  The heuristic estimated cost from node $n$ to the goal. f(n):  The total estimated cost of the cheapest solution through node $n$, calculated as:$f(n) = g(n) + h(n)$ A* Algorithm Steps Initialize the open set with the start node. Initialize a map to record the lowest cost to reach each node ($g$ value). While the open set is not empty: Pick the node with the lowest $f(n)$ value. If the node is the goal, reconstruct and return the path. Else, for each neighbor: Calculate tentative $g$ score. If this score is better than previously recorded, update it. Set neighbor's parent to the current node. If the ...