Question 3051
An image-processing routine applies a smoothing filter to a rectangular grid of integer pixel values. For each cell in the input grid, the smoothed grid contains the integer average (truncated toward zero, as with Java's int division) of that cell and its orthogonal neighbors — the cells directly above, below, to the left, and to the right, when they exist.
A corner cell therefore averages three values (itself and its two in-bounds orthogonal neighbors); an edge cell averages four; and an interior cell averages five. Diagonal neighbors are never included. The original grid must not be modified.
Write a static method gridSmooth that takes a rectangular 2-D array grid of non-negative integers (at least one row and one column; every row has the same length) and returns a new 2-D array of the same dimensions containing the smoothed values, as defined above.
Method Signature
public static int[][] gridSmooth(int[][] grid)
Example 1
Given the 3×4 grid on the left, the result is shown on the right. Each cell shows the full computation for reference.
| Input grid | Returned grid |
|---|---|
| |
For instance, the value at row 1, column 1 is \((6 + 8 + 2 + 3 + 1) / 5 = 20 / 5 = 4\) (itself, up, left, right, down — truncated). The value at row 0, column 0 is \((4 + 8 + 2) / 3 = 14 / 3 = 4\) (itself, right, down — truncated). The value at row 2, column 3 is \((9 + 5 + 7) / 3 = 21 / 3 = 7\).
Example 2
A 1×1 grid maps to itself: gridSmooth({{ 42 }}) returns {{ 42 }} (the sum is 42, divided by 1).
A 1×3 grid behaves as if every cell is on the top and bottom edge: gridSmooth({{ 3, 6, 9 }}) returns {{ 4, 6, 7 }}, since \((3+6)/2 = 4\), \((6+3+9)/3 = 6\), and \((9+6)/2 = 7\).
Main Solution
Sample Solution
public static int[][] gridSmooth(int[][] grid)
{
int rows = grid.length;
int cols = grid[0].length;
int[][] result = new int[rows][cols];
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
long sum = grid[r][c];
int n = 1;
if (r > 0)
{
sum = sum + grid[r - 1][c];
n = n + 1;
}
if (r < rows - 1)
{
sum = sum + grid[r + 1][c];
n = n + 1;
}
if (c > 0)
{
sum = sum + grid[r][c - 1];
n = n + 1;
}
if (c < cols - 1)
{
sum = sum + grid[r][c + 1];
n = n + 1;
}
result[r][c] = (int) (sum / n);
}
}
return result;
}
Scoring. Allocate a fresh int[rows][cols] so the original grid is untouched. Four independent boundary guards (not a single nested condition) keep the logic clear and match the natural 3/4/5 neighbor counts at corners, edges, and interior cells. Integer division at the end gives Java's truncated-toward-zero semantics automatically for non-negative inputs.
Teacher Explanation
Education Coach Advice
Traps
Answer images

