Grid and Hashes

In this problem, we just need to iterate thru the grid and calculate the average for each region, adding that to a hash table for each pixel, then iterate thru each key in the hash and create the new returning grid accordingly. Process takes O(9NM) where N and M are the dimensions of the grid. Code is down below, cheers, ACC.

Find the Grid of Region Average - LeetCode

3030. Find the Grid of Region Average
Medium

You are given a 0-indexed m x n grid image which represents a grayscale image, where image[i][j] represents a pixel with intensity in the range[0..255]. You are also given a non-negative integer threshold.

Two pixels image[a][b] and image[c][d] are said to be adjacent if |a - c| + |b - d| == 1.

A region is a 3 x 3 subgrid where the absolute difference in intensity between any two adjacent pixels is less than or equal to threshold.

All pixels in a region belong to that region, note that a pixel can belong to multiple regions.

You need to calculate a 0-indexed m x n grid result, where result[i][j] is the average intensity of the region to which image[i][j] belongs, rounded down to the nearest integer. If image[i][j] belongs to multiple regions, result[i][j] is the average of the rounded down average intensities of these regions, rounded down to the nearest integer. If image[i][j] does not belong to any region, result[i][j] is equal to image[i][j].

Return the grid result.

Example 1:

Input: image = [[5,6,7,10],[8,9,10,10],[11,12,13,10]], threshold = 3
Output: [[9,9,9,9],[9,9,9,9],[9,9,9,9]]
Explanation: There exist two regions in the image, which are shown as the shaded areas in the picture. The average intensity of the first region is 9, while the average intensity of the second region is 9.67 which is rounded down to 9. The average intensity of both of the regions is (9 + 9) / 2 = 9. As all the pixels belong to either region 1, region 2, or both of them, the intensity of every pixel in the result is 9. 
Please note that the rounded-down values are used when calculating the average of multiple regions, hence the calculation is done using 9 as the average intensity of region 2, not 9.67.

Example 2:

Input: image = [[10,20,30],[15,25,35],[20,30,40],[25,35,45]], threshold = 12
Output: [[25,25,25],[27,27,27],[27,27,27],[30,30,30]]
Explanation: There exist two regions in the image, which are shown as the shaded areas in the picture. The average intensity of the first region is 25, while the average intensity of the second region is 30. The average intensity of both of the regions is (25 + 30) / 2 = 27.5 which is rounded down to 27. All the pixels in row 0 of the image belong to region 1, hence all the pixels in row 0 in the result are 25. Similarly, all the pixels in row 3 in the result are 30. The pixels in rows 1 and 2 of the image belong to region 1 and region 2, hence their assigned value is 27 in the result.

Example 3:

Input: image = [[5,6,7],[8,9,10],[11,12,13]], threshold = 1
Output: [[5,6,7],[8,9,10],[11,12,13]]
Explanation: There does not exist any region in image, hence result[i][j] == image[i][j] for all the pixels.

Constraints:

  • 3 <= n, m <= 500
  • 0 <= image[i][j] <= 255
  • 0 <= threshold <= 255
Accepted
8,252
Submissions
19,223

public class PixelRegions
{
 public int numberRegions = 0;
 public long sumRegions = 0;
}
public int[][] ResultGrid(int[][] image, int threshold)
{
 Hashtable pixelMapperdRegions = new Hashtable();
 int KEY_CONST = image.Length + 1007;
 for (int row = 0; row < image.Length; row++)
 {
 for (int col = 0; col < image[row].Length; col++)
 {
 bool isRegion = true;
 long sum = 0;
 for (int r = 0; r < 3; r++)
 {
 for (int c = 0; c < 3; c++)
 {
 if (row + r < image.Length && col + c < image[row + r].Length)
 {
 if (r + 1 < 3 && row + r + 1 < image.Length && Math.Abs(image[row + r + 1][col + c] - image[row + r][col + c]) > threshold)
 {
 isRegion = false;
 break;
 }
 if (c + 1 < 3 && col + c + 1 < image[row + r].Length && Math.Abs(image[row + r][col + c + 1] - image[row + r][col + c]) > threshold)
 {
 isRegion = false;
 break;
 }
 sum += (long)image[row + r][col + c];
 }
 else
 {
 isRegion = false;
 break;
 }
 }
 if (!isRegion) break;
 }
 if (isRegion)
 {
 for (int r = 0; r < 3; r++)
 {
 for (int c = 0; c < 3; c++)
 {
 int key = (row + r) * KEY_CONST + col + c;
 if (!pixelMapperdRegions.ContainsKey(key)) pixelMapperdRegions.Add(key, new PixelRegions());
 PixelRegions pixelRegions = (PixelRegions)pixelMapperdRegions[key];
 pixelRegions.numberRegions++;
 pixelRegions.sumRegions += (long)Math.Floor(sum / 9.0);
 }
 }
 }
 }
 }
 int[][] retVal = new int[image.Length][];
 for (int row = 0; row < image.Length; row++)
 {
 retVal[row] = new int[image[row].Length];
 for (int col = 0; col < retVal[row].Length; col++)
 {
 int key = row * KEY_CONST + col;
 if (pixelMapperdRegions.ContainsKey(key))
 {
 PixelRegions pixelRegions = (PixelRegions)pixelMapperdRegions[key];
 int avg = (int)Math.Floor(pixelRegions.sumRegions * 1.0 / pixelRegions.numberRegions);
 retVal[row][col] = avg;
 }
 else
 {
 retVal[row][col] = image[row][col];
 }
 }
 }
 return retVal;
}


Comments

Post a Comment

[フレーム]

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. πŸ” Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...