WorkspaceProblem lab
ALGORITHM VISUALIZER

Shortest Path in a Grid

Opening the interactive workspace…

Understanding Shortest Grid Path

Find the fewest moves from the top-left cell to the bottom-right cell. Zero means open and one means blocked. Move up, down, left, or right. Return −1 if no path exists.

How it works

A BFS queue processes cells in increasing distance, so the first visit gives the shortest route.

Store distances when enqueuing cells and visit each open cell once. Stop when the destination is dequeued.

Try an example

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

Output: 4

Move down, right, right, then down.

Constraints

  • A nonempty rectangular grid of at most 8 × 8 cells.
  • Cells contain only 0 or 1.
  • Count moves, not visited cells; a single open cell needs 0 moves.

Use the simulator

Change the input, then choose Visualize input. Use Next and Previous to inspect each decision, or Play to advance automatically. Compare approaches and their complexity. Choose Try yourself to write JavaScript, select My code and Visualize code to inspect its execution, or Run Tests to check results.

Execution happens in your browser. Drafts are saved locally; avoid entering secrets or sensitive information.

Related concepts and complexity