LearnFrenzy
Sign in Take a free test

Python Coding Interview Questions · Coding Problems – Data Structures and Algorithms · Question 6

Shortest path in a grid with obstacles using BFS in Python Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Find the length of the shortest path from the top-left to the bottom-right of a grid ("." free, "#" wall), moving in four directions, and print the path drawn on the grid.

Solution
main.py Run
from collections import deque

def shortest(grid):
    rows, cols = len(grid), len(grid[0])
    start, goal = (0, 0), (rows - 1, cols - 1)
    parent = {start: None}
    queue = deque([start])
    while queue:
        r, c = queue.popleft()
        if (r, c) == goal:
            break
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == "." and (nr, nc) not in parent:
                parent[(nr, nc)] = (r, c)
                queue.append((nr, nc))
    if goal not in parent:
        return -1, grid
    path, cell = [], goal
    while cell:
        path.append(cell)
        cell = parent[cell]
    drawn = [list(row) for row in grid]
    for r, c in path:
        drawn[r][c] = "*"
    return len(path) - 1, ["".join(row) for row in drawn]

steps, picture = shortest(["..#..",
                           ".##.#",
                           "....."])
print(steps)
print("\n".join(picture))

Output Verified by running it on Python 3

6
*.#..
*##.#
*****

BFS explores in order of distance, and the parent map lets us walk back from the goal to draw the path. O(rows × cols).

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links