2025-08-21 08:08:30 +0000 UTC
Design Neighbor Sum Service
Categories:
Links
Code
class NeighborSum:
def __init__(self, grid: List[List[int]]):
self._adj = [0] * 101
self._diag = [0] * 101
rows, cols = len(grid), len(grid[0])
adj_moves = ((0, 1), (0, -1), (-1, 0), (1, 0))
diag_moves = ((-1, -1), (-1, 1), (1, -1), (1, 1))
for row in range(rows):
for col in range(cols):
val = grid[row][col]
for row_dlt, col_dlt in adj_moves:
adj_row, adj_col = row + row_dlt, col + col_dlt
if 0 <= adj_row < rows and 0 <= adj_col < cols:
self._adj[grid[adj_row][adj_col]] += val
for row_dlt, col_dlt in diag_moves:
diag_row, diag_col = row + row_dlt, col + col_dlt
if 0 <= diag_row < rows and 0 <= diag_col < cols:
self._diag[grid[diag_row][diag_col]] += val
def adjacentSum(self, value: int) -> int:
return self._adj[value]
def diagonalSum(self, value: int) -> int:
return self._diag[value]
# Your NeighborSum object will be instantiated and called as such:
# obj = NeighborSum(grid)
# param_1 = obj.adjacentSum(value)
# param_2 = obj.diagonalSum(value)