996. 01 Matrix — Distance to Nearest Zero

EasyGraphsGridBFSGraph

Given a matrix of 0s and 1s, return a matrix of the same size where each cell holds its distance (number of steps, moving 4-directionally) to the nearest 0. The input is JSON {mat} and is guaranteed to contain at least one 0.

Input: JSON {mat}.

Output: Nested array — the distance matrix.

Examples

Example 1
Input: {"mat":[[0,0,0],[0,1,0],[1,1,1]]}
Output: [[0,0,0],[0,1,0],[1,2,1]]
Explanation: Distances to the nearest 0.
Example 2
Input: {"mat":[[0]]}
Output: [[0]]
Explanation: Single zero.
Example 3
Input: {"mat":[[0,1],[1,0]]}
Output: [[0,1],[1,0]]
Explanation: Each 1 is adjacent to a 0.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →