Orthogonal Neighbor Grid Total
Problem statement
You are given an integer grid. Each cell is updated simultaneously using only values from the original grid.
For every existing orthogonal neighbor, add 1 to the cell if that neighbor has a strictly greater value, or subtract 1 if that neighbor has a strictly smaller value. An equal-valued neighbor contributes no change. Only cells immediately above, below, left or right are neighbors.
Return the sum of all cell values after one simultaneous update.
For this exercise, assume the same rule applies to any nonempty rectangular integer grid; there is no wrapping at the edges and no contribution from outside the grid. Return the total as a signed 64-bit integer.
Complete updatedGridTotal(grid). The requested output is the total, so you do not need to return the updated grid.
Function
updatedGridTotal(grid: int[][]) → longExamples
Example 1
grid = [[2,4,5],[1,7,8],[3,5,4]]return = 39This is the photographed initial grid. A simultaneous update gives [[2,5,5],[4,5,5],[3,4,6]]. Its total is 39; the total is independently derived from the printed rules.
Example 2
grid = [[5]]return = 5A single cell has no orthogonal neighbors, so its value and the total stay 5.
Example 3
grid = [[1,2,2]]return = 5The updated row is [2,1,2]. Equal neighboring values contribute no change, and the total remains 5.
Example 4
grid = [[-4,-4],[-1,2]]return = -7The updated grid is [[-3,-3],[-1,0]]. Negative numbers use the same strict comparisons; the total remains -7.
Constraints
- For this exercise, assume
1 <= rows, columns <= 200. - For this exercise, assume
-1,000,000 <= grid[r][c] <= 1,000,000. - The grid is rectangular and all entries are integers.
- The absolute total is at most 40,000,000,000 and fits in a signed 64-bit integer.