Nearest 1 in a binary matrix in C++


Given a binary matrix, we need to find the minimum distance from each cell to the nearest cell that contains 1.

Let's see an example.

Input

0 0 1
1 1 0
0 0 0

Output

1 1 0 0 0 1 1 1 2

The minimum distance is the one that is minimum from current cell row - 1 cell row + current cell column - 1 cell column.

Algorithm

  • Initialise the matrix of desired size.

  • Initialise another matrix of same size to store distance.

  • Iterate over the entire matrix

    .
    • If the current cell value is 1, then set the distance to 0 as distance from 1 to 1 is 0

    • If the current cell value is 0

      • Iterate over the entire matrix again

      • If the cell is 1, then calculate the distance from the current cell.

      • Update the minimum distance.

        .
  • Print the distance matrix.

Implementation

Following is the implementation of the above algorithm in C++

#include <bits/stdc++.h>

using namespace std;

vector<vector<int>> findNearest1Distance(vector<vector<int>>& matrix) {
   int rows = matrix.size();
   if (rows == 0) {
      return matrix;
   }
   int cols = matrix[0].size();
   vector<vector<int>> distance(rows, vector<int>(cols, INT_MAX));
   for (int i = 0; i < rows; i++) {
      for (int j = 0; j < cols; j++) {
         if (matrix[i][j] == 1) {
            distance[i][j] = 0;
         }else if (matrix[i][j] == 0) {
            for (int k = 0; k < rows; k++) {
               for (int l = 0; l < cols; l++) {
                  if (matrix[k][l] == 1) {
                     distance[i][j] = min(distance[i][j], abs(k - i) + abs(l - j));
                  }
               }
            }
         }
      }
   }
return distance;
}
int main() {
vector<vector<int>> matrix{
{0, 0, 1},
{1, 1, 0},
{0, 0, 0}
};
vector<vector<int>> result = findNearest1Distance(matrix);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << result[i][j] << " ";
}
cout << endl;
}
return 0;
}

Output

If you run the above code, then you will get the following result.

1 1 0
0 0 1
1 1 2

Updated on: 27-Oct-2021

157 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements