PracticeLevel 3: CollectionsEx 65. Shortest path in a grid
0/150 Solved(0%)
Level 3Exercise #65

Shortest path in a grid

Return the minimum unblocked steps from start to target in a 0/1 grid, or -1.

What you’ll practice

This Level 3 exercise focuses on deque BFS in the Collections curriculum. Solve the challenge prompt above using clear, idiomatic Python and the relevant language or standard-library tools.

Relevant Python reference: collections.deque.

Sample Test Cases

Example #1
Input:shortest_path([[0,0],[0,0]], (0,0), (1,1))
Output:2

Further Reading

Reference Solution

Reveal Reference Solution
def shortest_path(grid: list[list[int]], start: tuple[int,int], target: tuple[int,int]) -> int:
from collections import deque
queue = deque([(start, 0)])
seen = {start}
while queue:
(r, c), distance = queue.popleft()
if (r, c) == target:
return distance
for dr, dc in ((1,0),(-1,0),(0,1),(0,-1)):
nr, nc = r + dr, c + dc
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and not grid[nr][nc] and (nr,nc) not in seen:
seen.add((nr,nc)); queue.append(((nr,nc), distance+1))
return -1
Pro Tips & Keyboard Shortcuts
Color Theme
Ctrl + K then T

Open VS Code Color Theme Quick Pick to select from 20 dark and light themes.

Editor SettingsCtrl + K

Open practice settings drawer to toggle line numbers, indenting, font size & hints.

Search MenuCtrl + /

Expand sidebar menu, focus search bar, and highlight search text instantly.

Focus Code Editor
Esc or Ctrl + `

Instantly highlight and focus code editor from anywhere, restoring cursor right where you left off.

Normal ViewEsc

Collapse sidebar and close all popups or settings drawers for clean focus view.

solution.py· Python 3.11 WASM