call(back)
Algorithms & Data StructuresmediumSign in to star problems

Shortest Path Around Obstacles

The world is a grid: 0 is a free cell and 1 is an obstacle you can't pass through. Movement is one cell per step — up, down, left or right, plus the four diagonals when diagonal is true. Return the number of steps on the shortest path from src to dst (each given as [row, col]), or -1 when there is no path.

grid = [[0, 1, 0],
        [0, 1, 0],
        [0, 0, 0]]
shortestPathGrid(grid, [0, 0], [0, 2], false)  ->  6

shortestPathGrid([[0, 0], [0, 0]], [0, 0], [1, 1], true)  ->  1

A start or destination on an obstacle has no path.

Hints

Hint 1

Obstacles plus unit steps means BFS: the frontier expands in order of distance, so the first time you pop the destination, its depth is the answer.

Hint 2

Mark cells visited when you enqueue them, not when you pop them, or the queue fills with duplicates.

Asked at