Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Shortest Path in Binary Matrix

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1091" 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

Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1. A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that: All the visited cells of the path are 0. All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner). The length of a clear path is the number of visited cells of this path. Example 1: Input: grid = [[0,1],[1,0]] Output: 2 Example 2: Input: grid = [[0,0,0],[1,1,0],[1,1,0]] Output: 4 Example 3: Input: grid = [[1,0,0],[1,1,0],[1,1,0]] Output: -1 Constraints: n == grid.length n == grid[i].length 1 <= n <= 100 grid[i][j] is 0 or 1

Explanation

Here's the breakdown of the solution:

  • Breadth-First Search (BFS): Use BFS to explore the grid, starting from the top-left cell (0, 0). BFS guarantees finding the shortest path.
  • 8-Directional Movement: Consider all 8 adjacent cells as possible moves in each step.
  • Visited Tracking: Keep track of visited cells to avoid cycles and redundant exploration. Modify the grid itself to act as the visited array, improving space efficiency.

  • Runtime Complexity: O(N^2), where N is the dimension of the grid.

  • Storage Complexity: O(N^2) in the worst case, due to the queue potentially holding all cells of the grid.

Code

    from collections import deque

def shortest_path_binary_matrix(grid):
    """
    Finds the length of the shortest clear path in a binary matrix.

    Args:
        grid: A n x n binary matrix.

    Returns:
        The length of the shortest clear path, or -1 if no path exists.
    """

    n = len(grid)

    # If the start or end cell is blocked, there's no path.
    if grid[0][0] == 1 or grid[n - 1][n - 1] == 1:
        return -1

    # If the grid is just one cell and it is zero, the path length is 1
    if n == 1 and grid[0][0] == 0:
        return 1

    queue = deque([(0, 0, 1)])  # (row, col, path_length)
    grid[0][0] = 1  # Mark as visited

    directions = [
        (0, 1),  # Right
        (0, -1), # Left
        (1, 0),  # Down
        (-1, 0), # Up
        (1, 1),  # Down-Right
        (1, -1), # Down-Left
        (-1, 1), # Up-Right
        (-1, -1) # Up-Left
    ]

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

        if row == n - 1 and col == n - 1:
            return path_length

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

            if 0 <= new_row < n and 0 <= new_col < n and grid[new_row][new_col] == 0:
                grid[new_row][new_col] = 1  # Mark as visited
                queue.append((new_row, new_col, path_length + 1))

    return -1  # No path found

More from this blog

C

Chatmagic blog

2894 posts