C++ code to find center of inner box


Suppose we have a matrix of size n x m. Cells are either 'W' as white or 'B' as black. Some square inside the table with odd length was painted black. We have to find the center of this square.

So, if the input is like

WWBBBW
WWBBBW
WWBBBW
WWWWWW
WWWWWW

then the output will be (3, 1).

Steps

To solve this, we will follow these steps −

n := row count of matrix
m := column count of matrix
cnt := 0
X := 0
Y := 0
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:
         increase cnt by 1
         X := X + i
         Y := Y + j
X := X / cnt
Y := Y / cnt
return (Y, X)

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
void solve(vector<vector<char>> matrix){
   int n = matrix.size();
   int m = matrix[0].size();
   int cnt = 0, X = 0, Y = 0;
   for (int i = 0; i < n; i++){
      for (int j = 0; j < m; j++)
         if (matrix[i][j] == 'B')
            cnt++, X += i, Y += j;
   }
   X /= cnt;
   Y /= cnt;
   printf("%d, %d\n", Y, X);
}
int main(){
   vector<vector<char>> matrix = { { 'W', 'W', 'B', 'B', 'B', 'W' },
      { 'W', 'W', 'B', 'B', 'B', 'W' }, { 'W', 'W', 'B', 'B', 'B', 'W' },
      { 'W', 'W', 'W', 'W', 'W', 'W' }, { 'W', 'W', 'W', 'W', 'W', 'W' } };
   solve(matrix);
}

Input

{ { 'W', 'W', 'B', 'B', 'B', 'W' },
   { 'W', 'W', 'B', 'B', 'B', 'W' }, { 'W', 'W', 'B', 'B', 'B', 'W' },
   { 'W', 'W', 'W', 'W', 'W', 'W' }, { 'W', 'W', 'W', 'W', 'W', 'W' } }

Output

3, 1

Updated on: 29-Mar-2022

275 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements