Graph Traversal

Lee Algorithm for Shortest Path

Lee's algorithm, a classic application of Breadth-First Search (BFS), efficiently finds the shortest path in a grid, making it a fundamental concept for maze-solving and robotics problems.

Lee Algorithm in Python

Here is a Python implementation of Lee's algorithm to find the shortest path in a maze from a source to a destination.

from collections import deque

def lee_algorithm(grid, src, dest):
    if not grid or not grid[0]:
        return -1

    rows, cols = len(grid), len(grid[0])
    visited = [[False] * cols for _ in range(rows)]
    queue = deque([(src, 0)])
    visited[src[0]][src[1]] = True

    row_num = [-1, 0, 0, 1]
    col_num = [0, -1, 1, 0]

    while queue:
        (pt, dist) = queue.popleft()

        if pt == dest:
            return dist

        for i in range(4):
            row = pt[0] + row_num[i]
            col = pt[1] + col_num[i]

            if (row >= 0 and row < rows and col >= 0 and col < cols and
                    grid[row][col] == 1 and not visited[row][col]):
                visited[row][col] = True
                queue.append(((row, col), dist + 1))

    return -1  # Destination not reachable

AI Coach Hint: Lee's algorithm is essentially a Breadth-First Search on a grid. The use of a queue is crucial as it ensures that we explore the grid level by level, which guarantees finding the shortest path in an unweighted grid.

Related Algorithm Guides

Explore more algorithm interview guides powered by AI coaching

Ethical Boundary Interview Discussion
AI-powered interview preparation guide
Coding Interview
AI-powered interview preparation guide
Professional Conduct Interview Questions
AI-powered interview preparation guide
Object Oriented Design Interview Questions And Answers
AI-powered interview preparation guide