Class NeighborSum
-
- All Implemented Interfaces:
public final class NeighborSum3242 - Design Neighbor Sum Service\.
Easy
You are given a
n x n2D arraygridcontaining distinct elements in the range <code>0, n<sup>2</sup> - 1</code>.Implement the
neighborSumclass:neighborSum(int [][]grid)initializes the object.int adjacentSum(int value)returns the sum of elements which are adjacent neighbors ofvalue, that is either to the top, left, right, or bottom ofvalueingrid.int diagonalSum(int value)returns the sum of elements which are diagonal neighbors ofvalue, that is either to the top-left, top-right, bottom-left, or bottom-right ofvalueingrid.
Example 1:
Input:
"neighborSum", "adjacentSum", "adjacentSum", "diagonalSum", "diagonalSum"
[[[0, 1, 2, 3, 4, 5, 6, 7, 8]], 1, 4, 4, 8]
Output: null, 6, 16, 16, 4
Explanation:
The adjacent neighbors of 1 are 0, 2, and 4.
The adjacent neighbors of 4 are 1, 3, 5, and 7.
The diagonal neighbors of 4 are 0, 2, 6, and 8.
The diagonal neighbor of 8 is 4.
Example 2:
Input:
"neighborSum", "adjacentSum", "diagonalSum"
[[[1, 2, 0, 3, 4, 7, 15, 6, 8, 9, 10, 11, 12, 13, 14, 5]], 15, 9]
Output: null, 23, 45
Explanation:
The adjacent neighbors of 15 are 0, 10, 7, and 6.
The diagonal neighbors of 9 are 4, 12, 14, and 15.
Constraints:
3 <= n == grid.length == grid[0].length <= 10<code>0 <= gridj<= n<sup>2</sup> - 1</code>
All
grid[i][j]are distinct.valueinadjacentSumanddiagonalSumwill be in the range <code>0, n<sup>2</sup> - 1</code>.At most <code>2 * n<sup>2</sup></code> calls will be made to
adjacentSumanddiagonalSum.
-
-
Constructor Summary
Constructors Constructor Description NeighborSum(Array<IntArray> grid)
-
Method Summary
Modifier and Type Method Description final IntegeradjacentSum(Integer value)final IntegerdiagonalSum(Integer value)-
-
Method Detail
-
adjacentSum
final Integer adjacentSum(Integer value)
-
diagonalSum
final Integer diagonalSum(Integer value)
-
-
-
-