Problem 275
Distance to Nearest Zero
Medium · 20 pts · Matrix, Breadth-First Search, Dynamic Programming
Problem
You are given a grid of 0's and 1's that contains at least one 0. For every cell, find the distance to the nearest 0, where one step moves to a neighbouring cell up, down, left or right. Cells containing 0 have distance 0. Print the grid of distances. Running a separate search from every cell is too slow. Instead, run one multi-source BFS: put all 0 cells in the queue at distance 0 and spread outwards; each cell gets its distance the first time it is reached.
Input
First line: R and C. Next R lines: C values, each 0 or 1.
Output
Print R lines with C distances each.
Constraints
1 <= R, C <= 300
Example input
3 3 0 0 0 0 1 0 1 1 1
Example output
0 0 0 0 1 0 1 2 1
Explanation
Every 0 has distance 0, and the 1's next to a 0 have distance 1. The 1 in the middle of the bottom row has the 1 above it and the 1's on its sides as neighbours, but no 0, so it is 2 steps from the nearest 0.