#K34072. Distance to the Nearest Zero
Distance to the Nearest Zero
Distance to the Nearest Zero
You are given an \(m \times n\) binary matrix \(\textbf{mat}\) consisting of 0's and 1's. Your task is to compute a distance matrix \(\textbf{dist}\) of the same dimensions where each element \(\textbf{dist}[i][j]\) represents the minimum distance from cell \((i, j)\) to any cell containing a 0.
The distance between two adjacent cells is considered to be 1, and you may only move up, down, left, or right.
Constraints:
- The matrix has at least one 0.
- \(1 \le m, n \le 10^4\) (with a reasonable total number of cells)
It is guaranteed that there is at least one 0 in the matrix.
Example:
Input: 3 3 0 0 0 0 1 0 0 0 0</p>Output: 0 0 0 0 1 0 0 0 0
Input: 3 3 0 0 0 0 1 0 1 1 1
Output: 0 0 0 0 1 0 1 2 1
inputFormat
The first line of input contains two integers \(m\) and \(n\) representing the number of rows and columns of the matrix.
The next \(m\) lines each contain \(n\) integers (either 0 or 1) separated by spaces, representing the rows of the matrix.
outputFormat
Output the resulting distance matrix with \(m\) rows. Each row should contain \(n\) integers separated by a space, where each integer represents the minimal distance to a 0 from that cell.
## sample3 3
0 0 0
0 1 0
0 0 0
0 0 0
0 1 0
0 0 0
</p>