Program to check if number of compass usage to get out of a maze is enough in Python

In this problem, we need to determine if we can escape from a maze using a compass at most k times. The maze is represented as a matrix where 'S' is the starting position, 'D' is the destination (exit), '-' represents walkable paths, and 'O' represents blocked cells. The compass is used when we have multiple path choices at any position.

Understanding the Problem

The key insight is that we only need to use the compass when we have multiple valid moves from our current position. If there's only one valid path, we can move without using the compass.

Algorithm Approach

We'll use a depth-first search (DFS) approach with backtracking ?

  • Find all valid neighboring positions (not blocked and not the previous position)
  • If multiple choices exist, use the compass (decrement k)
  • If only one choice exists, move without using the compass
  • Recursively explore all possible paths

Implementation

def can_escape_maze(grid, k):
    rows, cols = len(grid), len(grid[0])
    
    # Find starting position
    start_pos = None
    for i in range(rows):
        for j in range(cols):
            if grid[i][j] == 'S':
                start_pos = (i, j)
                break
    
    def get_valid_neighbors(pos, parent):
        """Get all valid neighboring positions"""
        x, y = pos
        neighbors = []
        
        # Check all four directions: up, down, left, right
        directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
        
        for dx, dy in directions:
            new_x, new_y = x + dx, y + dy
            
            # Check bounds and validity
            if (0 <= new_x < rows and 0 <= new_y < cols and
                grid[new_x][new_y] != 'O' and (new_x, new_y) != parent):
                neighbors.append((new_x, new_y))
        
        return neighbors
    
    def dfs_search(curr_pos, remaining_compass, parent, visited):
        """DFS to find if destination is reachable"""
        x, y = curr_pos
        
        # Check if we reached the destination
        if grid[x][y] == 'D':
            return True
        
        # Mark current position as visited
        visited.add(curr_pos)
        
        # Get valid neighboring positions
        neighbors = get_valid_neighbors(curr_pos, parent)
        valid_neighbors = [pos for pos in neighbors if pos not in visited]
        
        # Determine if compass is needed
        use_compass = len(valid_neighbors) > 1
        
        # If compass is needed but we don't have any left, return False
        if use_compass and remaining_compass <= 0:
            visited.remove(curr_pos)
            return False
        
        # Explore each valid neighbor
        for neighbor in valid_neighbors:
            new_compass_count = remaining_compass - 1 if use_compass else remaining_compass
            
            if dfs_search(neighbor, new_compass_count, curr_pos, visited):
                visited.remove(curr_pos)
                return True
        
        # Backtrack
        visited.remove(curr_pos)
        return False
    
    # Start DFS from starting position
    return dfs_search(start_pos, k, None, set())

# Test with the given example
grid = [
    ['-', 'O', '-', 'O', '-', '-', '-', '-', '-', '-', 'O'],
    ['-', 'O', 'D', '-', 'O', '-', 'O', 'O', 'O', '-', 'O'],
    ['-', 'O', 'O', '-', 'O', '-', 'O', 'S', '-', '-', '-'],
    ['-', '-', '-', '-', '-', '-', 'O', 'O', 'O', 'O', '-']
]

k = 3
result = can_escape_maze(grid, k)
print(f"Can escape with {k} compass uses: {result}")
Can escape with 3 compass uses: True

How It Works

The algorithm works as follows ?

  1. Find Starting Position: Locate the 'S' cell in the grid
  2. DFS Exploration: Use depth-first search to explore all possible paths
  3. Compass Logic: Use compass only when multiple valid moves are available
  4. Backtracking: If a path doesn't lead to destination, backtrack and try other paths
  5. Visited Tracking: Maintain a visited set to avoid cycles

Key Points

  • Compass is used only when there are multiple valid path choices
  • Single path movements don't require compass usage
  • Blocked cells ('O') and previously visited cells are avoided
  • The algorithm returns True if any path leads to destination within compass limit

Example Walkthrough

In the given maze, starting from 'S' at position (2,7), the algorithm explores paths toward 'D' at (1,2). With 3 compass uses available, it can navigate through the maze by making strategic choices at intersections.

Conclusion

This solution uses DFS with backtracking to explore all possible paths in the maze. The compass is used efficiently only when multiple path choices exist, making it possible to determine if escape is feasible within the given compass usage limit.

Updated on: 2026-03-26T00:50:14+05:30

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements