Associated Course(s):
DSA- Online
Geeks Classes in Noida- (Summer-Weekdays)

Given a binary matrix of size **N x M**. The task is to find the distance of nearest 1 in the matrix for each cell. The distance is calculated as **|i _{1} – i_{2}| + |j_{1} – j_{2}|**, where i

**Input:**

The first line of input is an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of 2 lines. The first line of each test case contains two integers M and N denoting the number of rows and columns of matrix. Then in the next line are N*M space separated values of the matrix (mat) .

**Output:**

For each test case in a new line print the required distance matrix in a single line separated by space.

**User Task:**

The task is to complete the function **nearest**() which finds the nearest cell with 1.

**Constraints:**

1 <= T <= 20

1 <= N, M <= 20

**Example:
Input:**

2

2 2

1 0 0 1

1 2

1 1

**Output:**

0 1 1 0

0 0

**Explanation:
Testcase 1:**

1 0

0 1

0 at {0, 1} and 0 at {1, 0} are at 1 distance from 1s at {0, 0} and {1, 1} respectively.

If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.

agness | 122 |

aman1931998 | 102 |

Survivor | 100 |

uchitnitk | 96 |

lonecoder | 95 |

KshatriyaYash | 1066 |

nikhil_sojan | 1032 |

lonecoder | 1030 |

mazumderrohit8 | 899 |

SumitSingh27 | 832 |

blackshadows | 5327 |

Ibrahim Nash | 5215 |

akhayrutdinov | 5111 |

mb1973 | 4492 |

Quandray | 4444 |

Login to report an issue on this page.