Distance Of Nearest Cell Having 1 In A Binary Matrix

You have been given a binary matrix 'MAT' containing only 0’s and 1’s of size N x M. You need to find the distance of the nearest cell having 1 in the matrix for each cell.

The distance is calculated as |i1 – i2| + |j1 – j2|, where i1, j1 are the coordinates of the current cell and i2, j2 are the coordinates of the nearest cell having value 1.
Note :
You can only move in four directions which are : Up, Down, Left and Right.
For example :
If N = 3, M = 4

and mat[ ][ ] = { 0, 0, 0, 1,
                  0, 0, 1, 1,
                  0, 1, 1, 0 }

then the output matrix will be

3  2  1  0
2  1  0  0
1  0  0  1
Input Format:
The first line contains an integer 'T' which denotes the number of test cases or queries to be run. Then the test cases are as follows.

The first line of each test case contains two space-separated integers ‘N’ and ‘M’ which denotes the size of the matrix.

The ‘N’ lines of each test case contain ‘M’ space-separated elements of the matrix.  
Output Format:
For each test case, print a matrix of the same size containing the distance of the nearest cell having ‘1’ for each cell.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 5
1 <= N <= 2*10^2
1 <= M <= 2*10^2

Where ‘T’ is the number of test cases, ‘N’ is the number of rows in the matrix and ‘M’ is the number of columns in the matrix.
AnswerBot
1y

Given a binary matrix, find the distance of the nearest cell having 1 in the matrix for each cell.

  • Use BFS to traverse the matrix and find the nearest cell having 1 for each cell.

  • Initialize the output ...read more

CodingNinjas
author
2y

The better approach is to do a BFS starting from all the 1s in the given matrix. The distance of all the 1s is zero and for all the adjacent the minimum distance is one more than this.

Create a queue o...read more

CodingNinjas
author
2y
Brute Force
  1. Traverse the matrix for all N*M cells one by one.
  2. For every cell find the closest cell which contains 1.
  3. Update the minimum distance.
  4. Fill the minimum distance in the matrix.
Space Complexity: ...read more
CodingNinjas
author
2y
Breadth-First Search

The basic idea of this approach is to use multi-source breadth first search. We will do bfs considering all the cells with value 1 as starting nodes. We can use an auxiliary queue ...read more

Add answer anonymously...
Dunzo Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter