InferenceAI

Enter at least two characters to search.

Start free

Shortest Grid Path

mediumGraphs25 min25 XP

grid contains 0 (open) and 1 (wall). Moving up, down, left or right costs one step. Return the minimum number of steps from the top-left cell to the bottom-right cell, or -1 if it is unreachable (including when either cell is a wall).

Examples

EXAMPLE WALKTHROUGHaround the wall

A guided view of the published example, not a trace of your code.

INPUT[[[0,0,0],[1,1,0],[0,0,0]]]
TASKshortest_grid_path()
EXPECTED OUTPUT4

Start with the input values shown in this example.

Example 1 of 3

Input: grid = [[0,0,0],[1,1,0],[0,0,0]]

Output: 4

Explanation: around the wall

Input: grid = [[0,1],[1,0]]

Output: -1

Explanation: blocked

Input: grid = [[0]]

Output: 0

Explanation: single cell

Hint 1

Breadth-first search explores cells in order of distance, so the first time you reach the goal is optimal.

Topics

DSAGraphsPython