classNeighborSum { private: vector<pair<int, int>> cache; public: NeighborSum(vector<vector<int>>& grid) { int n = grid.size(); cache.resize(n * n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int cntAdj = 0, cntDia = 0; for (int k = 0; k < 4; k++) { int x = i + adj[k][0], y = j + adj[k][1]; if (x >= 0 && x < n && y >= 0 && y < n) { cntAdj += grid[x][y]; } x = i + dia[k][0], y = j + dia[k][1]; if (x >= 0 && x < n && y >= 0 && y < n) { cntDia += grid[x][y]; } } cache[grid[i][j]] = {cntAdj, cntDia}; } } }
classNeighborSum: def__init__(self, grid: List[List[int]]): n = len(grid) self.cache = [[0, 0] for _ inrange(n * n)] for i inrange(n): for j inrange(n): for th, (x, y) inenumerate(direction): if0 <= x + i < n and0 <= y + j < n: self.cache[grid[i][j]][th // 4] += grid[x + i][y + j]
var direction = []struct{x, y int}{{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {-1, 1}, {1, -1}, {1, 1}} type Value [][2]int
type NeighborSum struct { cache Value }
funcConstructor(grid [][]int) NeighborSum { n := len(grid) var neighborSum NeighborSum neighborSum.cache = make(Value, n * n) for i, row := range grid { for j, v := range row { for k, d := range direction { x, y := i + d.x, j + d.y if x >= 0 && x < n && y >= 0 && y < n { neighborSum.cache[v][k / 4] += grid[x][y] } } } } return neighborSum }
func(this *NeighborSum) AdjacentSum(value int) int { return this.cache[value][0] }
func(this *NeighborSum) DiagonalSum(value int) int { return this.cache[value][1] }