1047. Heat Map Smoother

Easy1.5 points estimatedMatrix3 hints

A greenhouse sensor grid reports a temperature in heat[r][c] for every position. Before drawing a map, the technician smooths it: each cell of the new grid becomes the average of the old values in the 3 x 3 block centred on that cell, using only the cells that actually lie inside the grid (so corners average 4 values and edges average 6).

Return the smoothed grid. All averages must be computed from the original readings, never from values that were already smoothed. Answers within 1e-6 of the exact average are accepted. Aim for time proportional to the number of cells.

Example 1

Input:
heat = [[10,20,30]]
Output:
[[15,20,25]]
Explanation:

In a single row each cell averages itself with its horizontal neighbours: (10+20)/2 = 15, (10+20+30)/3 = 20 and (20+30)/2 = 25.

Example 2

Input:
heat = [[8,0],[0,4]]
Output:
[[3,3],[3,3]]
Explanation:

Every cell of a 2 x 2 grid sees all four values, so each result is (8+0+0+4)/4 = 3.

Constraints

1 ≤ rows, cols ≤ 20
-1000.0 ≤ heat[r][c] ≤ 1000.0

How this problem is judged

Answers
Numbers are accepted within a tolerance of 1.0E-6: |answer - expected| <= 1.0E-6 x max(1, |expected|).
Tolerance
0.000001

Expected complexity

Time
O(rows*cols)
Space
O(rows*cols)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…