The “Lonely Pixel I” problem involves finding pixels in a grid (2D matrix) that are “lonely.” A lonely pixel is defined as a black pixel ('B'
) that is the only black pixel in its row and the only black pixel in its column.
Problem Statement
Given a grid of characters consisting of black pixels ('B'
) and white pixels ('W'
), the goal is to count how many lonely black pixels exist in the grid.
C# Implementation
Here’s a C# solution to this problem:
using System;
public class LonelyPixelCounter
{
public static int CountLonelyPixels(char[][] picture)
{
int m = picture.Length; // Number of rows
int n = picture[0].Length; // Number of columns
int[] rowCount = new int[m]; // Count of 'B's in each row
int[] colCount = new int[n]; // Count of 'B's in each column
// First pass: Count 'B's in each row and column
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (picture[i][j] == 'B')
{
rowCount[i]++;
colCount[j]++;
}
}
}
int lonelyPixelCount = 0;
// Second pass: Count lonely pixels
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (picture[i][j] == 'B' && rowCount[i] == 1 && colCount[j] == 1)
{
lonelyPixelCount++;
}
}
}
return lonelyPixelCount; // Return the total count of lonely pixels
}
public static void Main(string[] args)
{
char[][] picture = new char[][]
{
new char[] { 'W', 'B', 'W' },
new char[] { 'W', 'W', 'W' },
new char[] { 'B', 'W', 'W' }
};
int result = CountLonelyPixels(picture);
Console.WriteLine($"The number of lonely pixels is: {result}");
}
}
Explanation
-
Data Structure:
- The grid (picture) is represented as a jagged array (
char[][]
), where each inner array corresponds to a row of pixels.
- The grid (picture) is represented as a jagged array (
-
CountLonelyPixels Method:
- This method calculates the number of lonely black pixels in the grid.
-
Row and Column Count Arrays:
rowCount
: An array that keeps track of the number of black pixels ('B'
) in each row.colCount
: An array that keeps track of the number of black pixels in each column.
-
First Pass:
- Iterate through each cell in the grid.
- For each black pixel found, increment the respective count in both
rowCount
andcolCount
.
-
Second Pass:
- Iterate through the grid again to check for lonely pixels.
- A pixel is considered lonely if:
- It is a black pixel (
'B'
). - It is the only black pixel in its row (i.e.,
rowCount[i] == 1
). - It is the only black pixel in its column (i.e.,
colCount[j] == 1
).
- It is a black pixel (
- If these conditions are met, increment the
lonelyPixelCount
.
-
Return Value:
- After both passes, the method returns the total count of lonely black pixels.
-
Main Method:
- The
Main
method creates a sample grid and callsCountLonelyPixels
, then prints the result.
- The
Usage
You can modify the picture
variable in the Main
method to test different configurations. This implementation efficiently counts lonely pixels by making two passes over the grid, ensuring optimal performance.