Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

BFS Shortest Path in Python

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is BFS Shortest Path in Python. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Apple Maps represents a simplified walking area as a rectangular grid. Each cell contains 0 for walkable terrain or 1 for a blocked area. Given a start cell and destination cell, return the shortest path between them using four-directional movement: up, down, left, or right.

The returned path must include both the start and destination coordinates. If multiple shortest paths exist, return any one of them. If the destination cannot be reached, return an empty list.

Formal Specification

Implement shortest_path(grid, start, destination), where grid is a non-empty list of equal-length lists containing integers, and start and destination are coordinate lists [row, column]. Return a list of coordinate lists in traversal order, or [] when no route exists.

Constraints

  • 1 <= rows, columns <= 500
  • grid contains only 0 and 1
  • start and destination are valid walkable coordinates
  • Movement is limited to four directions
  • Return any one shortest path when multiple paths exist

Function Signature

def shortest_path(grid, start, destination):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output