Skip to content
BytePatterns

Shortest Clear Grid Path

MediumMatrix & Grid#bfs#grid-traversal#shortest-path~25m

Problem

A warehouse robot moves on a grid where 0 marks an open cell and 1 marks a shelf. Each move goes one cell up, down, left or right, and only onto open cells. Return the fewest moves needed to go from the top-left cell to the bottom-right cell, or -1 if it cannot be done. The grid has at least one cell.

Examples

Input:  grid = [[0, 0, 0, 0],
                [1, 1, 0, 1],
                [0, 0, 0, 0],
                [0, 1, 1, 0]]
Output: 6
Why:    right twice, down twice, right once, down once
Input:  grid = [[0, 1],
                [1, 0]]
Output: -1
Why:    both neighbours of the start are shelves
Input:  grid = [[0]]
Output: 0
Why:    edge case, the robot already stands on the goal

Hints

0 / 3

Stuck on the idea rather than the code? Shortest Path, Unweighted covers it.