# C++ program to find minimum number of operations needed to make all cells at r row c columns black

Suppose we have two numbers r, c and a grid of size n x m. Some cells are in black and remaining are white. In one operation, we can select some black cells and can do exactly one of these two −

• Color all cells in its row black, or
• color all cells in its column black.

We have to find the minimum number of operations needed to make the cells in row r and column c black. If impossible, return -1.

So, if the input is like

 W B W W W B B B W B W W B B B

r = 0 and c = 3

then the output will be 1, because we can change the first row to make this like −

 B B B B B B B B W B W W B B B

## Steps

To solve this, we will follow these steps −

n := row count of grid
m := column count of grid
ans := inf
for initialize i := 0, when i < n, update (increase i by 1), do:
for initialize j := 0, when j < m, update (increase j by 1), do:
if matrix[i, j] is same as 'B', then:
ans := minimum of ans and (1 if i and r are different, otherwise 0) + (1 if j and                c are different, otherwise 0)
if ans > 2, then:
return -1
Otherwise
return ans

## Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

int solve(vector<vector<char>> matrix, int r, int c) {
int n = matrix.size();
int m = matrix[0].size();
int ans = 999999;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (matrix[i][j] == 'B') {
ans = min(ans, (i != r) + (j != c));
}
}
}
if (ans > 2) {
return -1;
}
else
return ans;
}
int main() {
vector<vector<char>> matrix = { { 'W', 'B', 'W', 'W', 'W' }, { 'B', 'B', 'B', 'W', 'B'          }, { 'W', 'W', 'B', 'B',          'B' } };
int r = 0, c = 3;
cout << solve(matrix, r, c) << endl;
}

## Input

{ { 'W', 'B', 'W', 'W', 'W' }, { 'B', 'B', 'B', 'W', 'B' }, { 'W', 'W', 'B', 'B', 'B' } }, 0, 3

## Output

1


Updated on: 03-Mar-2022

155 Views