Skip to content

ORIGINAL CODING QUESTION

Shortest blocked-grid exit route

Cells encode 0=open, 1=blocked, 2=start and 3=exit. Return the fewest four-side moves from start to exit, or -1 if unreachable.

Open practice workspace

Original exercise · medium. Editorial role relevance does not imply a company has asked this question.

Input and output

rows cols, then rows×cols cell values in row-major order. Print one integer.

Constraints

1 ≤ rows,cols ≤ 12; at least two cells; exactly one start and one exit; cell tokens 0..3.

Example 1

Input

2 3 2 0 3 1 1 0

Output

2

Two moves reach the exit along the top row.

Example 2

Input

1 3 2 1 3

Output

-1

The wall blocks all routes.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

All moves have equal cost.

Hint 2

Breadth-first search visits cells by distance.

Hint 3

Mark a cell on enqueue to prevent repeated work.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →