# Lonely Pixel II in C++

Suppose we have a picture consisting of black and white pixels, we have to find the number of black pixels, which are present at row R and column C. That is aligned with all the following rules −

• R and C will contain exactly N black pixels

• For all rows, that have a black pixel at column C, they should be exactly the same as row R.

Here the picture is represented by a 2D char array consisting of 'B' and 'W', for the black and white pixels respectively.

If the input is like −

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

And N = 3, then the output will be 6. Because all of the bold 'B' are the black pixels all 'B's at column 1 and 3. Now if we take 'B' at row R = 0 and column C = 1 so for an example: Rule 1, row R = 0 and column C = 1 both have exactly N ‘B’ pixels. and Rule 2, the rows have ‘B’ pixel at column C = 1 are row 0, row 1 and row 2. They are exactly the same as row R = 0.

To solve this, we will follow these steps −

• ret := 0

• Define one map r another map c

• n := row count of p, m := column count of p

• 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 p[i, j] is same as 'B', then −

• insert j into r[i]

• insert i into c[j]

• for initialize i := 0, when i < n, update (increase i by 1), do −

• for initialize j := 0, when j < m and i is in r, update (increase j by 1), do −

• if p[i, j] is same as 'B' and size of r[i] is same as N and size of c[j] is same as N, then −

• ok := true

• for each x in c[j], do

• if r[x] is not equal to r[i], then −

• ok := false

• Come out from the loop

• ret := ret + ok

• return ret

## Example (C++)

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int findBlackPixel(vector<vector<char>>& p, int N) {
int ret = 0;
unordered_map <int, set <int> > r, c;
int n = p.size();
int m = p[0].size();
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(p[i][j] == 'B'){
r[i].insert(j);
c[j].insert(i);
}
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < m && r.count(i); j++){
if(p[i][j] == 'B' && r[i].size() == N && c[j].size() == N){
bool ok = true;
for(auto& x : c[j]){
if(r[x] != r[i]){
ok = false;
break;
}
}
ret += ok;
}
}
}
return ret;
}
};
main(){
Solution ob;
vector<vector<char>> v = {{'W','B','W','B','B','W'},{'W','B','W','B','B','W'},{'W','B','W','B' ,'B','W'},{'W','W','B','W','B','W'}};
cout << (ob.findBlackPixel(v, 3));
}

## Input

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

## Output

6

Updated on: 16-Nov-2020

58 Views