Skip to content

ORIGINAL CODING QUESTION

Shortest route with diagonal steps

A floor plan marks open floor with 0 and furniture with 1. From an open cell you may step to any of the eight surrounding cells, diagonals included, as long as it is open. Return the fewest steps from the top-left cell to the bottom-right cell. Return 0 if they are the same open cell and -1 if either corner is furniture or no route exists.

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.

Constraints

1 ≤ rows,cols ≤ 8; each cell is 0 or 1.

Example 1

Input

3 3 0 0 0 1 1 0 1 1 0

Output

3

Right, then diagonally down-right, then down: three steps.

Example 2

Input

2 2 0 1 1 1

Output

-1

The destination corner is blocked.

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

Every step costs the same, so breadth-first search gives shortest distances.

Hint 2

Each cell has up to eight neighbours instead of four.

Hint 3

Check both corners before searching and mark cells when you enqueue them.

Practice this question

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

Open practice workspaceBrowse the question library →