Open In App

Count Lonely Pixel II

Last Updated : 28 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an m x n picture consisting of black ‘B’ and white ‘W’ pixels and an integer target, return the number of black lonely pixels.

A black lonely pixel is a character ‘B’ that located at a specific position (r, c) where:

  • Row r and column c both contain exactly target black pixels.
  • For all rows that have a black pixel at column c, they should be exactly the same as row r.

Examples:

Input: picture = [[“W”,”B”,”W”,”B”,”B”,”W”],[“W”,”B”,”W”,”B”,”B”,”W”],[“W”,”B”,”W”,”B”,”B”,”W”],[“W”,”W”,”B”,”W”,”B”,”W”]], target = 3
Output: 6
Explanation: All the green ‘B’ are the black pixels we need (all ‘B’s at column 1 and 3).
Take ‘B’ at row r = 0 and column c = 1 as an example:

  • Rule 1, row r = 0 and column c = 1 both have exactly target = 3 black pixels.
  • Rule 2, the rows have black pixel at column c = 1 are row 0, row 1 and row 2. They are exactly the same as row r = 0.

Input: picture = [[“W”,”W”,”B”],[“W”,”W”,”B”],[“W”,”W”,”B”]], target = 1
Output: 0

Approach:

Count the number of black pixels in each row and column. For each row, create a string representing the pattern of black and white pixels in that row. Count the number of occurrences of each row pattern.

Iterate over the picture again and check for lonely black pixels. A black pixel is lonely if:

  • The row containing the pixel has exactly ‘target’ black pixels.
  • The row pattern containing the pixel has exactly ‘target’ occurrences.
  • The column containing the pixel has exactly ‘target’ black pixels.

Steps to solve this problem:

  • Create variables res, m, and n to store the result, number of rows, and number of columns respectively.
  • Create vectors ro and col to store counts of black pixels in rows and columns respectively.
  • Create vector rs to store string patterns of rows.
  • Create an unordered map mp to store the count of each pattern in rows.
  • Loop Through Rows and Columns:
    • Iterate over each row of the image.
    • For each row, iterate over each column.
    • Count the black pixels in each row and column and store string patterns of rows in rs.
    • Update the count of each pattern in mp.
  • Check for Lonely Black Pixels:
    • Iterate over each row of the image.
    • If the count of black pixels in the row equals the target t and the count of the row’s pattern in mp equals t, proceed.
    • Inside this condition, iterate over each column of the current row.
    • If the pixel is black and the count of black pixels in the column equals t, increment the result res.
  • Return the final count of lonely black pixels.

Below is the implementation of the above idea:

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

// Function to find the number of black lonely pixels
int findBlackPixel(vector<vector<char> >& v, int t)
{
    int res = 0;
    int m = v.size();
    int n = v[0].size();

    // vector for saving the count of black pixels in rows
    vector<int> ro(m, 0);
    // vector for saving the count of back pixels in columns
    vector<int> col(n, 0);
    // vector to store the string pattern of the row
    vector<string> rs(m);
    // map to store the count of each pattern in rows(read
    // second condition of lonely pixel)
    unordered_map<string, int> mp;
    for (int i = 0; i < m; i++) {
        string s = "";
        for (int j = 0; j < n; j++) {
            if (v[i][j] == 'B') {
                ro[i]++;
                col[j]++;
            }
            s += v[i][j];
        }
        // save the string and increment value in map
        rs[i] = s;
        mp[s]++;
    }
    for (int i = 0; i < m; i++) {
        // row should have black pixels equal to the target
        // if row is havng pixels equal to the target then
        // its following pattner should alos have the count
        // equal to the target
        if (ro[i] == t && mp[rs[i]] == t) {
            for (int j = 0; j < n; j++) {
                if (v[i][j] == 'B' && col[j] == t)
                    res++;
            }
        }
        else
            continue;
    }
    // answer
    return res;
}

int main()
{

    vector<vector<char> > picture
        = { { 'W', 'B', 'W', 'B', 'B', 'W' },
            { 'W', 'B', 'W', 'B', 'B', 'W' },
            { 'W', 'B', 'W', 'B', 'B', 'W' },
            { 'W', 'W', 'B', 'W', 'B', 'W' } };
    int target = 3;

    cout << findBlackPixel(picture, target);
}
Java
import java.util.HashMap;
import java.util.Map;

public class BlackLonelyPixels {
    // Function to find the number of black lonely pixels
    public static int findBlackPixel(char[][] v, int t)
    {
        int res = 0;
        int m = v.length;
        int n = v[0].length;

        // Array for saving the count of black pixels in
        // rows
        int[] ro = new int[m];
        // Array for saving the count of black pixels in
        // columns
        int[] col = new int[n];
        // Array to store the string pattern of the row
        String[] rs = new String[m];
        // Map to store the count of each pattern in rows
        // (read second condition of lonely pixel)
        Map<String, Integer> mp = new HashMap<>();

        for (int i = 0; i < m; i++) {
            StringBuilder s = new StringBuilder();
            for (int j = 0; j < n; j++) {
                if (v[i][j] == 'B') {
                    ro[i]++;
                    col[j]++;
                }
                s.append(v[i][j]);
            }
            // Save the string and increment value in map
            rs[i] = s.toString();
            mp.put(s.toString(),
                   mp.getOrDefault(s.toString(), 0) + 1);
        }

        for (int i = 0; i < m; i++) {
            // Row should have black pixels equal to the
            // target If row is having pixels equal to the
            // target then its following pattern should also
            // have the count equal to the target
            if (ro[i] == t && mp.get(rs[i]) == t) {
                for (int j = 0; j < n; j++) {
                    if (v[i][j] == 'B' && col[j] == t)
                        res++;
                }
            }
        }

        // Answer
        return res;
    }

    public static void main(String[] args)
    {
        char[][] picture
            = { { 'W', 'B', 'W', 'B', 'B', 'W' },
                { 'W', 'B', 'W', 'B', 'B', 'W' },
                { 'W', 'B', 'W', 'B', 'B', 'W' },
                { 'W', 'W', 'B', 'W', 'B', 'W' } };
        int target = 3;

        System.out.println(findBlackPixel(picture, target));
    }
}

// This code is contributed by shivamgupta0987654321
Python3
def find_black_pixel(picture, t):
    res = 0
    m = len(picture)
    n = len(picture[0])

    # Lists to store the count of black pixels in rows and columns
    ro = [0] * m
    col = [0] * n
    # Dictionary to store the count of each row's pattern
    rs = []
    # Dictionary to store the count of each pattern in rows
    mp = {}

    for i in range(m):
        s = ""
        for j in range(n):
            if picture[i][j] == 'B':
                ro[i] += 1
                col[j] += 1
            s += picture[i][j]
        rs.append(s)
        if s in mp:
            mp[s] += 1
        else:
            mp[s] = 1

    for i in range(m):
        # Check if the row has black pixels equal to the target
        if ro[i] == t and mp[rs[i]] == t:
            for j in range(n):
                # Check for 'B' pixels that are lonely (column count equals target)
                if picture[i][j] == 'B' and col[j] == t:
                    res += 1

    return res


if __name__ == "__main__":
    picture = [
        ['W', 'B', 'W', 'B', 'B', 'W'],
        ['W', 'B', 'W', 'B', 'B', 'W'],
        ['W', 'B', 'W', 'B', 'B', 'W'],
        ['W', 'W', 'B', 'W', 'B', 'W']
    ]
    target = 3

    result = find_black_pixel(picture, target)
    print(result)
JavaScript
// Function to find the number of black lonely pixels
function findBlackPixel(v, t) {
    let res = 0;
    let m = v.length;
    let n = v[0].length;

    // Array for saving the count of black pixels in rows
    let ro = new Array(m).fill(0);
    // Array for saving the count of black pixels in columns
    let col = new Array(n).fill(0);
    // Array to store the string pattern of the row
    let rs = new Array(m);
    // Map to store the count of each pattern in rows 
   (read second condition of lonely pixel)
    let mp = new Map();
    for (let i = 0; i < m; i++) {
        let s = "";
        for (let j = 0; j < n; j++) {
            if (v[i][j] === 'B') {
                ro[i]++;
                col[j]++;
            }
            s += v[i][j];
        }
        // Save the string and increment value in map
        rs[i] = s;
        mp.set(s, (mp.get(s) || 0) + 1);
    }
    for (let i = 0; i < m; i++) {
        // Row should have black pixels equal to the target
        // If row is having pixels equal to the target then
        // its following pattern should also have the count
        // equal to the target
        if (ro[i] === t && mp.get(rs[i]) === t) {
            for (let j = 0; j < n; j++) {
                if (v[i][j] === 'B' && col[j] === t)
                    res++;
            }
        } else {
            continue;
        }
    }
    // Answer
    return res;
}

// Example usage
let picture = [
    ['W', 'B', 'W', 'B', 'B', 'W'],
    ['W', 'B', 'W', 'B', 'B', 'W'],
    ['W', 'B', 'W', 'B', 'B', 'W'],
    ['W', 'W', 'B', 'W', 'B', 'W']
];
let target = 3;

console.log(findBlackPixel(picture, target));

Output
6

Time complexity: O(m * n), where m is the number of rows in the picture and n is the number of columns in the picture.
Auxiliary space: O(m * n)




Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads