Skip to content
BIASED
Back to topic

Optional

BFS shortest path on a grid

NumPy/queue: find shortest-path length and recover the route on a 5×5 grid with one obstacle.

Version
v1
Minutes
~20
Evidence
Self-check in the notebook

Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.

Download .ipynb

Download the notebook and run it locally. Its environment requirements are listed inside.

Notebook contents

Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.

Agents · BFS кратчайший путь / BFS shortest path

Activity version: 1 · Seed: n/a · Данные: сетка 5×55\times 5, старт (0,0)(0,0), цель (4,4)(4,4), препятствие (2,2)(2,2).

Ходы: вверх/вниз/влево/вправо.

Ожидаемые числа
Quantity Value Tolerance
длина пути (рёбра) 88 exact
достижимость True exact
Самопроверка в ноутбуке

Не влияет на mastery.

import numpy as np
from collections import deque
 
n = 5
blocked = {(2, 2)}
start, goal = (0, 0), (4, 4)
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
 
dist = {start: 0}
prev = {start: None}
q = deque([start])
while q:
    r, c = q.popleft()
    if (r, c) == goal:
        break
    for dr, dc in dirs:
        nr, nc = r + dr, c + dc
        nxt = (nr, nc)
        if not (0 <= nr < n and 0 <= nc < n):
            continue
        if nxt in blocked or nxt in dist:
            continue
        dist[nxt] = dist[(r, c)] + 1
        prev[nxt] = (r, c)
        q.append(nxt)
 
assert goal in dist
path_len = dist[goal]
print("path_len", path_len)
assert path_len == 8
print("OK: BFS shortest path")
Самопроверка в ноутбуке
  • длина пути = 8
  • клетка (2,2)(2,2) не посещена