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 |
|---|
{ { 4, 8, 12, 0 },
{ 2, 6, 3, 5 },
{ 10, 1, 7, 9 } }
| { { 4, 7, 5, 5 },
{ 5, 4, 6, 4 },
{ 4, 6, 5, 7 } }
|
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\).