Searching
Algorithms are evaluated along the following dimensions:
- Completeness: Is the algorithm guaranteed to find a solution if one exists? Does it correctly report failure if no solution exists? \text{Yes} & \text{if a solution is guaranteed when it exists,} \\ \text{No} & \text{otherwise.} \end{cases} $$
- Cost Optimality (Admissibility): Does the algorithm find the solution with the lowest path cost among all possible solutions? \text{Yes} & \text{if the solution is cost-optimal,} \\ \text{No} & \text{otherwise.} \end{cases} $$
- Time Complexity: How long does it take to find a solution? This is often measured in terms of the number of states and actions considered.
- Space Complexity: How much memory is required to perform the search?
Time and space complexity are measured using:
- b: Maximum branching factor of the search tree (number of successors of a node that need to be considered).
- d: Depth of the least-cost solution.
- m: Maximum number of actions in any path (can be ∞).
Uninformed Search
When no information about the goal is available, uninformed search algorithms are used. These algorithms explore the state space systematically without any prior knowledge of the goal's location or cost.
Breadth-First Search (BFS)
Intuition: Explore all nodes at the present depth before moving on to nodes at the next depth level. This ensures that the first solution found is the shallowest one.
- Completeness:
- Cost Optimality:
BFS guarantees the shallowest (and thus the shortest in unweighted graphs) solution first.
- Time Complexity:
Every node up to depth d is explored.
- Space Complexity:
All nodes at the current depth are stored in memory.
-
What It Is Used For: Finding the shortest path in unweighted graphs, level-order traversal of trees, and scenarios where the solution is likely to be shallow.
-
Best Use Cases:
- Puzzle solving (e.g., Rubik's cube, sliding tile puzzles).
- Shortest path in unweighted grids (e.g., mazes).
- Web crawling (exploring links level by level).
-
Pseudocode:
def BFS(start): queue = Queue() queue.enqueue(start) visited = set() visited.add(start) while not queue.is_empty(): node = queue.dequeue() if is_goal(node): return node for successor in successors(node): if successor not in visited: visited.add(successor) queue.enqueue(successor) return None -
Important Things to Note:
- BFS is memory-intensive for deep or wide trees, as it stores all nodes at the current depth.
- Not suitable for weighted graphs unless all edge costs are equal.
Iterative Deepening Search (IDS)
Intuition: Combine the benefits of BFS and DFS by performing a series of depth-limited searches with increasing depth limits. This ensures that the solution is found with the memory efficiency of DFS while maintaining the optimality of BFS.
- Completeness:
- Cost Optimality:
- Time Complexity:
Although nodes are revisited, the overhead is minimal because most nodes are at the deepest level.
- Space Complexity:
Only the current path and its siblings are stored in memory.
-
What It Is Used For: Finding the shortest path in large state spaces where memory is limited.
-
Best Use Cases:
- Game tree searches (e.g., chess, checkers).
- Scenarios where the solution depth is unknown but memory is constrained.
-
Pseudocode:
def IDS(start): depth = 0 while True: result = DLS(start, depth) if result != "cutoff": return result depth += 1 def DLS(node, depth_limit): if is_goal(node): return node if depth_limit == 0: return "cutoff" cutoff_occurred = False for successor in successors(node): result = DLS(successor, depth_limit - 1) if result == "cutoff": cutoff_occurred = True elif result != "failure": return result return "cutoff" if cutoff_occurred else "failure" -
Important Things to Note:
- IDS repeats work from previous iterations but is far more memory-efficient than BFS.
- Preferred over BFS when memory is a constraint and the solution depth is unknown.
Uniform Cost Search (UCS)
aka "Dijkstra's Algorithm" Intuition: Explore nodes in order of increasing path cost from the start node. This ensures that the first time a goal node is reached, it is via the lowest-cost path.
- Completeness:
- Cost Optimality:
UCS always expands the least-cost node first, guaranteeing optimality.
- Time Complexity:
where C(^)* is the cost of the optimal solution and ε is the minimum step cost.
- Space Complexity:
All explored nodes are stored in memory.
-
What It Is Used For: Finding the lowest-cost path in weighted graphs where edge costs vary.
-
Best Use Cases:
- Navigation systems (e.g., GPS routing).
- Network routing (e.g., OSPF, Dijkstra's algorithm).
- Any scenario where path cost is a critical factor.
-
Pseudocode:
def UCS(start): priority_queue = PriorityQueue() priority_queue.enqueue(start, 0) visited = set() cost_so_far = {start: 0} while not priority_queue.is_empty(): node = priority_queue.dequeue() if is_goal(node): return node if node in visited: continue visited.add(node) for successor in successors(node): new_cost = cost_so_far[node] + step_cost(node, successor) if successor not in cost_so_far or new_cost < cost_so_far[successor]: cost_so_far[successor] = new_cost priority_queue.enqueue(successor, new_cost) return None -
Important Things to Note:
- UCS explores nodes in order of increasing path cost, making it suitable for weighted graphs.
- Can be slow if the graph is large or edge costs vary widely.
- Requires a priority queue to efficiently retrieve the least-cost node.
Bidirectional Search
Intuition: Run two simultaneous searches—one forward from the start node and one backward from the goal node—hoping that they meet in the middle. This can significantly reduce the search space.
- Completeness:
- Cost Optimality:
- Time Complexity:
The search space is effectively halved.
- Space Complexity:
Nodes from both searches are stored in memory.
-
What It Is Used For: Finding the shortest path in large state spaces where the goal is known.
-
Best Use Cases:
- Puzzle solving (e.g., sliding tile puzzles).
- Pathfinding in grids (e.g., robot navigation).
-
Pseudocode:
def BidirectionalSearch(start, goal): forward_queue = Queue() forward_queue.enqueue(start) backward_queue = Queue() backward_queue.enqueue(goal) forward_visited = {start: 0} backward_visited = {goal: 0} while not forward_queue.is_empty() or not backward_queue.is_empty(): # Forward search node = forward_queue.dequeue() if node in backward_visited: return reconstruct_path(node, forward_visited, backward_visited) for successor in successors(node): if successor not in forward_visited: forward_visited[successor] = forward_visited[node] + 1 forward_queue.enqueue(successor) # Backward search node = backward_queue.dequeue() if node in forward_visited: return reconstruct_path(node, forward_visited, backward_visited) for predecessor in predecessors(node): if predecessor not in backward_visited: backward_visited[predecessor] = backward_visited[node] + 1 backward_queue.enqueue(predecessor) return None -
Important Things to Note:
- Requires a way to reverse the goal state (i.e., generate predecessors).
- Can be memory-intensive if both searches grow large before meeting.
- Not straightforward to implement for weighted graphs.
Depth-First Search (DFS)
Intuition: Explore as far as possible along a branch before backtracking. This makes DFS memory-efficient but not guaranteed to find the shortest path.
- Completeness:
DFS may get stuck in infinite loops or miss solutions in infinite trees.
- Cost Optimality:
DFS finds the first solution, not necessarily the best one.
- Time Complexity:
where m is the maximum depth of the tree.
- Space Complexity:
Only the current path is stored in memory.
-
What It Is Used For: Exploring all possible paths, backtracking, and scenarios where memory is limited.
-
Best Use Cases:
- Maze solving (e.g., finding a path from start to exit).
- Topological sorting of directed acyclic graphs (DAGs).
- Checking for cycles in graphs.
-
Pseudocode:
def DFS(start): stack = Stack() stack.push(start) visited = set() while not stack.is_empty(): node = stack.pop() if is_goal(node): return node if node not in visited: visited.add(node) for successor in successors(node): stack.push(successor) return None -
Important Things to Note:
- DFS is memory-efficient but not guaranteed to find the shortest path.
- Can be combined with cycle detection to avoid infinite loops.
- Often used as a subroutine in other algorithms (e.g., IDS).
Depth-Limited Search (DLS)
Intuition: A variant of DFS with a depth limit to prevent infinite loops and excessive memory usage. If the solution is beyond the depth limit, it is not found.
- Completeness:
- Cost Optimality:
DLS finds the first solution within the depth limit, not necessarily the best one.
- Time Complexity:
where l is the depth limit.
- Space Complexity:
Only the current path and its siblings are stored in memory.
-
What It Is Used For: Limiting the depth of DFS to avoid infinite paths or excessive memory usage.
-
Best Use Cases:
- Scenarios where the solution depth is known or bounded.
- Game tree searches with a known maximum depth.
-
Pseudocode:
def DLS(node, depth_limit): if is_goal(node): return node if depth_limit == 0: return "cutoff" cutoff_occurred = False for successor in successors(node): result = DLS(successor, depth_limit - 1) if result == "cutoff": cutoff_occurred = True elif result != "failure": return result return "cutoff" if cutoff_occurred else "failure" -
Important Things to Note:
- Avoids the pitfalls of infinite loops in DFS.
- May miss solutions if the depth limit is too restrictive.
Informed Search
When hints about the goal are available (e.g., an estimate of the distance or cost to the goal), informed search algorithms are used. These algorithms leverage a heuristic function h(n) to guide the search toward the goal more efficiently.
Greedy Best-First Search
Intuition: Expand the node that appears to be closest to the goal based on the heuristic function h(n). This approach is greedy and does not consider the cost of the path taken so far.
- Completeness:
Greedy best-first search can get stuck in loops or miss solutions.
- Cost Optimality:
It does not guarantee the lowest-cost solution.
- Time Complexity:
but can be much faster with a good heuristic.
- Space Complexity:
All explored nodes are stored in memory.
-
What It Is Used For: Finding solutions quickly when the heuristic is informative and the path cost is not critical.
-
Best Use Cases:
- Pathfinding in games (e.g., NPC navigation).
- Navigation systems where the heuristic (e.g., straight-line distance) is a good estimate.
-
Pseudocode:
def GreedyBestFirstSearch(start, goal): priority_queue = PriorityQueue() priority_queue.enqueue(start, h(start, goal)) visited = set() while not priority_queue.is_empty(): node = priority_queue.dequeue() if is_goal(node): return node if node in visited: continue visited.add(node) for successor in successors(node): if successor not in visited: priority_queue.enqueue(successor, h(successor, goal)) return None -
Important Things to Note:
- Performance heavily depends on the quality of the heuristic h(n).
- Can be combined with other algorithms (e.g., A*) for better performance.
A* Search
Intuition: Combine the cost to reach a node g(n) and the heuristic estimate of the cost to the goal h(n) to guide the search. A* is both complete and optimal if the heuristic is admissible.
-
- Cost to reach the current node
-
- Cost to reach the goal
-
Completeness:
- Cost Optimality:
- Time Complexity:
but can be much faster with a good heuristic.
- Space Complexity:
All explored nodes are stored in memory.
-
What It Is Used For: Finding the lowest-cost path with an informative heuristic.
-
Best Use Cases:
- Navigation systems (e.g., GPS routing).
- Puzzle solving (e.g., 8-puzzle, 15-puzzle).
- Robotics (e.g., path planning).
-
Pseudocode:
def AStarSearch(start, goal): priority_queue = PriorityQueue() priority_queue.enqueue(start, h(start, goal)) visited = set() cost_so_far = {start: 0} while not priority_queue.is_empty(): node = priority_queue.dequeue() if is_goal(node): return node if node in visited: continue visited.add(node) for successor in successors(node): new_cost = cost_so_far[node] + step_cost(node, successor) if successor not in cost_so_far or new_cost < cost_so_far[successor]: cost_so_far[successor] = new_cost priority = new_cost + h(successor, goal) priority_queue.enqueue(successor, priority) return None -
Important Things to Note:
- A* is optimal and complete if h(n) is admissible and consistent.
- The heuristic h(n) must never overestimate the cost to the goal.
- Requires a priority queue to efficiently retrieve the node with the lowest f(n) = g(n) + h(n).
Bidirectional A* Search
Intuition: Run two simultaneous A* searches—one forward from the start node and one backward from the goal node—hoping that they meet in the middle. This can significantly reduce the search space.
- Completeness:
- Cost Optimality:
- Time Complexity:
The search space is effectively halved.
- Space Complexity:
Nodes from both searches are stored in memory.
-
What It Is Used For: Speeding up A* by searching from both the start and goal simultaneously.
-
Best Use Cases:
- Large state spaces where the goal is known (e.g., pathfinding in grids).
- Scenarios where the heuristic is informative in both directions.
-
Pseudocode:
def BidirectionalAStar(start, goal): forward_queue = PriorityQueue() forward_queue.enqueue(start, h(start, goal)) backward_queue = PriorityQueue() backward_queue.enqueue(goal, h(goal, start)) forward_cost = {start: 0} backward_cost = {goal: 0} forward_visited = {start: h(start, goal)} backward_visited = {goal: h(goal, start)} while not forward_queue.is_empty() or not backward_queue.is_empty(): # Forward search node = forward_queue.dequeue() if node in backward_visited: return reconstruct_path(node, forward_cost, backward_cost) for successor in successors(node): new_cost = forward_cost[node] + step_cost(node, successor) if successor not in forward_cost or new_cost < forward_cost[successor]: forward_cost[successor] = new_cost priority = new_cost + h(successor, goal) forward_queue.enqueue(successor, priority) forward_visited[successor] = priority # Backward search node = backward_queue.dequeue() if node in forward_visited: return reconstruct_path(node, forward_cost, backward_cost) for predecessor in predecessors(node): new_cost = backward_cost[node] + step_cost(predecessor, node) if predecessor not in backward_cost or new_cost < backward_cost[predecessor]: backward_cost[predecessor] = new_cost priority = new_cost + h(predecessor, start) backward_queue.enqueue(predecessor, priority) backward_visited[predecessor] = priority return None -
Important Things to Note:
- Requires a way to reverse the goal state and heuristic.
- Can be complex to implement, especially for weighted graphs.
- Not always faster than A* if the heuristic is not informative in both directions.
Iterative Deepening A* (IDA*)
Intuition: Combine the benefits of A* and iterative deepening. Perform a series of depth-first searches with increasing cost thresholds, where the threshold is the minimum f(n) = g(n) + h(n) that exceeded the previous threshold.
- Completeness:
- Cost Optimality:
- Time Complexity:
but depends on the heuristic.
- Space Complexity:
Only the current path is stored in memory.
-
What It Is Used For: Finding the lowest-cost path in large state spaces with limited memory.
-
Best Use Cases:
- Puzzle solving (e.g., 15-puzzle).
- Scenarios where memory is constrained but optimality is required.
-
Pseudocode:
def IDAStar(start, goal): threshold = h(start, goal) path = [start] while True: result, new_threshold = Search(path, 0, threshold, goal) if result == "found": return path if new_threshold == ∞: return None threshold = new_threshold def Search(path, g, threshold, goal): node = path[-1] f = g + h(node, goal) if f > threshold: return "cutoff", f if is_goal(node): return "found", threshold min_threshold = ∞ for successor in successors(node): if successor not in path: path.append(successor) result, new_threshold = Search(path, g + step_cost(node, successor), threshold, goal) if result == "found": return "found", threshold if new_threshold < min_threshold: min_threshold = new_threshold path.pop() return "cutoff", min_threshold -
Important Things to Note:
- IDA* repeats work but is memory-efficient, making it suitable for large state spaces.
- The cost threshold increases iteratively, ensuring optimality.
Beam Search
Intuition: A heuristic-based search that limits the number of nodes expanded at each level to a fixed number k (the beam width). This trades optimality for speed and memory efficiency.
- Completeness:
Beam search may miss solutions due to the beam width limit.
- Cost Optimality:
It does not guarantee the lowest-cost solution.
- Time Complexity:
where k is the beam width.
- Space Complexity:
Only the best k nodes at each level are stored in memory.
-
What It Is Used For: Finding approximate solutions in large state spaces with limited memory.
-
Best Use Cases:
- Machine translation (e.g., neural machine translation).
- Speech recognition.
- Other natural language processing (NLP) tasks.
-
Pseudocode:
def BeamSearch(start, goal, k): beam = [start] while beam: successors = [] for node in beam: if is_goal(node): return node successors.extend(expand(node)) # Select top-k successors based on heuristic successors.sort(key=lambda node: h(node, goal)) beam = successors[:k] return None -
Important Things to Note:
- The beam width k controls the trade-off between quality and resource usage.
- Beam search is not guaranteed to find the optimal solution but is useful for large state spaces.