Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Nearest Exit from Entrance in Maze

Updated
4 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1926" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at. In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit. Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists. Example 1: Input: maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2] Output: 1 Explanation: There are 3 exits in this maze at [1,0], [0,2], and [2,3]. Initially, you are at the entrance cell [1,2]. - You can reach [1,0] by moving 2 steps left. - You can reach [0,2] by moving 1 step up. It is impossible to reach [2,3] from the entrance. Thus, the nearest exit is [0,2], which is 1 step away. Example 2: Input: maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0] Output: 2 Explanation: There is 1 exit in this maze at [1,2]. [1,0] does not count as an exit since it is the entrance cell. Initially, you are at the entrance cell [1,0]. - You can reach [1,2] by moving 2 steps right. Thus, the nearest exit is [1,2], which is 2 steps away. Example 3: Input: maze = [[".","+"]], entrance = [0,0] Output: -1 Explanation: There are no exits in this maze. Constraints: maze.length == m maze[i].length == n 1 <= m, n <= 100 maze[i][j] is either '.' or '+'. entrance.length == 2 0 <= entrancerow < m 0 <= entrancecol < n entrance will always be an empty cell.

Explanation

Here's the solution to find the shortest path to the nearest exit in a maze:

  • BFS Approach: Utilize Breadth-First Search (BFS) to explore the maze layer by layer, starting from the entrance. This guarantees finding the shortest path.
  • Exit Condition: During BFS, check if the current cell is an exit (border cell, not the entrance). If found, return the number of steps taken to reach it.
  • Visited Set: Use a set to keep track of visited cells to avoid cycles and redundant exploration.

  • Runtime Complexity: O(m*n), where m and n are the dimensions of the maze.

  • Storage Complexity: O(m*n)

Code

    from collections import deque

def nearestExit(maze, entrance):
    """
    Finds the nearest exit from the entrance in a maze.

    Args:
        maze: A list of lists of strings representing the maze.
        entrance: A list of two integers representing the entrance coordinates.

    Returns:
        The number of steps in the shortest path to the nearest exit, or -1 if no such path exists.
    """
    m = len(maze)
    n = len(maze[0])
    start_row, start_col = entrance
    queue = deque([(start_row, start_col, 0)])  # (row, col, steps)
    visited = set([(start_row, start_col)])
    directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]

    while queue:
        row, col, steps = queue.popleft()

        # Check if it's an exit (border cell, not the entrance)
        if (row == 0 or row == m - 1 or col == 0 or col == n - 1) and (row, col) != (start_row, start_col):
            return steps

        # Explore neighbors
        for dr, dc in directions:
            new_row = row + dr
            new_col = col + dc

            if 0 <= new_row < m and 0 <= new_col < n and maze[new_row][new_col] == '.' and (new_row, new_col) not in visited:
                queue.append((new_row, new_col, steps + 1))
                visited.add((new_row, new_col))

    return -1  # No exit found

More from this blog

C

Chatmagic blog

2894 posts