Skip to content

ORIGINAL CODING QUESTION

Total distance to nearest zero

For each cell measure the fewest four-side moves to any zero cell; one cells are walkable. Return the sum of these distances.

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; each cell is 0 or 1; adjacency uses four sides, not diagonals. At least one zero cell exists.

Example 1

Input

2 2 0 1 1 1

Output

4

Distances 0,1,1,2 sum to 4.

Example 2

Input

1 3 0 1 0

Output

1

Only the middle cell contributes 1.

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

Treat all zero cells as initial sources.

Hint 2

One breadth-first search propagates minimum distances.

Hint 3

Add the resulting distance of every cell.

Practice this question

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

Open practice workspaceBrowse the question library →