LeetCode 3242: Design Neighbor Sum Service (Grid Simulation)
LeetCode 3242DesignGridToday we solve LeetCode 3242 - Design Neighbor Sum Service.
Source: https://leetcode.com/problems/design-neighbor-sum-service/
English
Problem Summary
Design a data structure initialized with an n x n grid containing distinct values. Support queries: sum of adjacent neighbors (up/down/left/right) and diagonal neighbors for a given value.
Key Insight
Values are unique, so precompute value -> (row, col). Then each query checks up to 4 fixed directions and runs in O(1).
Algorithm
Store grid and a hash map from value to coordinate. For each query, find coordinate from map, iterate directional offsets, validate bounds, and accumulate grid values.
Complexity
Initialization: O(n^2). Each query: O(1). Extra space: O(n^2).
Reference Implementations (Java / Go / C++ / Python / JavaScript)
class NeighborSum {
private final int[][] g;
private final java.util.Map pos = new java.util.HashMap<>();
public NeighborSum(int[][] grid) {
g = grid;
for (int i = 0; i < g.length; i++)
for (int j = 0; j < g[0].length; j++)
pos.put(g[i][j], new int[]{i, j});
}
public int adjacentSum(int value) { return sum(value, new int[][]{{-1,0},{1,0},{0,-1},{0,1}}); }
public int diagonalSum(int value) { return sum(value, new int[][]{{-1,-1},{-1,1},{1,-1},{1,1}}); }
private int sum(int value, int[][] d) {
int[] p = pos.get(value);
int r = p[0], c = p[1], n = g.length, ans = 0;
for (int[] x : d) {
int nr = r + x[0], nc = c + x[1];
if (nr >= 0 && nr < n && nc >= 0 && nc < n) ans += g[nr][nc];
}
return ans;
}
} type NeighborSum struct { g [][]int; pos map[int][2]int }
func Constructor(grid [][]int) NeighborSum { p:=map[int][2]int{}; for i:=range grid { for j:=range grid[i] { p[grid[i][j]]=[2]int{i,j} } }; return NeighborSum{grid,p} }
func (n *NeighborSum) adjacentSum(value int) int { return n.sum(value, [][2]int{{-1,0},{1,0},{0,-1},{0,1}}) }
func (n *NeighborSum) diagonalSum(value int) int { return n.sum(value, [][2]int{{-1,-1},{-1,1},{1,-1},{1,1}}) }
func (n *NeighborSum) sum(value int, d [][2]int) int { p:=n.pos[value]; r,c:=p[0],p[1]; ans:=0; N:=len(n.g); for _,x:=range d { nr,nc:=r+x[0],c+x[1]; if nr>=0&&nr=0&&nc class NeighborSum {
vector> g; unordered_map> pos;
int sum(int v, const vector>& d){ auto [r,c]=pos[v]; int n=g.size(), ans=0; for(auto [dr,dc]:d){ int nr=r+dr,nc=c+dc; if(0<=nr&&nr>& grid): g(grid){ for(int i=0;i class NeighborSum:
def __init__(self, grid):
self.g = grid
self.pos = {grid[i][j]:(i,j) for i in range(len(grid)) for j in range(len(grid))}
def adjacentSum(self, value):
return self._sum(value, [(-1,0),(1,0),(0,-1),(0,1)])
def diagonalSum(self, value):
return self._sum(value, [(-1,-1),(-1,1),(1,-1),(1,1)])
def _sum(self, value, d):
r, c = self.pos[value]
n = len(self.g)
ans = 0
for dr, dc in d:
nr, nc = r + dr, c + dc
if 0 <= nr < n and 0 <= nc < n:
ans += self.g[nr][nc]
return ansvar NeighborSum = function(grid) {
this.g = grid;
this.pos = new Map();
for (let i = 0; i < grid.length; i++) for (let j = 0; j < grid[0].length; j++) this.pos.set(grid[i][j], [i, j]);
};
NeighborSum.prototype.adjacentSum = function(value) { return this.sum(value, [[-1,0],[1,0],[0,-1],[0,1]]); };
NeighborSum.prototype.diagonalSum = function(value) { return this.sum(value, [[-1,-1],[-1,1],[1,-1],[1,1]]); };
NeighborSum.prototype.sum = function(value, d) {
const [r, c] = this.pos.get(value); const n = this.g.length; let ans = 0;
for (const [dr, dc] of d) { const nr = r + dr, nc = c + dc; if (nr >= 0 && nr < n && nc >= 0 && nc < n) ans += this.g[nr][nc]; }
return ans;
};中文
题目概述
设计一个服务,初始化时给定一个元素互不相同的 n x n 网格。查询某个值对应位置的上下左右邻居和,以及四个对角邻居和。
核心思路
因为值唯一,先建立 value -> (row, col) 映射。每次查询只检查固定 4 个方向,因此是常数时间。
算法步骤
保存原网格和位置映射。查询时先定位坐标,再按方向偏移尝试访问邻居,边界内就累加。
复杂度分析
初始化 O(n^2),单次查询 O(1),额外空间 O(n^2)。
多语言参考实现(Java / Go / C++ / Python / JavaScript)
class NeighborSum {
private final int[][] g;
private final java.util.Map pos = new java.util.HashMap<>();
public NeighborSum(int[][] grid) {
g = grid;
for (int i = 0; i < g.length; i++)
for (int j = 0; j < g[0].length; j++)
pos.put(g[i][j], new int[]{i, j});
}
public int adjacentSum(int value) { return sum(value, new int[][]{{-1,0},{1,0},{0,-1},{0,1}}); }
public int diagonalSum(int value) { return sum(value, new int[][]{{-1,-1},{-1,1},{1,-1},{1,1}}); }
private int sum(int value, int[][] d) {
int[] p = pos.get(value);
int r = p[0], c = p[1], n = g.length, ans = 0;
for (int[] x : d) {
int nr = r + x[0], nc = c + x[1];
if (nr >= 0 && nr < n && nc >= 0 && nc < n) ans += g[nr][nc];
}
return ans;
}
} type NeighborSum struct { g [][]int; pos map[int][2]int }
func Constructor(grid [][]int) NeighborSum { p:=map[int][2]int{}; for i:=range grid { for j:=range grid[i] { p[grid[i][j]]=[2]int{i,j} } }; return NeighborSum{grid,p} }
func (n *NeighborSum) adjacentSum(value int) int { return n.sum(value, [][2]int{{-1,0},{1,0},{0,-1},{0,1}}) }
func (n *NeighborSum) diagonalSum(value int) int { return n.sum(value, [][2]int{{-1,-1},{-1,1},{1,-1},{1,1}}) }
func (n *NeighborSum) sum(value int, d [][2]int) int { p:=n.pos[value]; r,c:=p[0],p[1]; ans:=0; N:=len(n.g); for _,x:=range d { nr,nc:=r+x[0],c+x[1]; if nr>=0&&nr=0&&nc class NeighborSum {
vector> g; unordered_map> pos;
int sum(int v, const vector>& d){ auto [r,c]=pos[v]; int n=g.size(), ans=0; for(auto [dr,dc]:d){ int nr=r+dr,nc=c+dc; if(0<=nr&&nr>& grid): g(grid){ for(int i=0;i class NeighborSum:
def __init__(self, grid):
self.g = grid
self.pos = {grid[i][j]:(i,j) for i in range(len(grid)) for j in range(len(grid))}
def adjacentSum(self, value):
return self._sum(value, [(-1,0),(1,0),(0,-1),(0,1)])
def diagonalSum(self, value):
return self._sum(value, [(-1,-1),(-1,1),(1,-1),(1,1)])
def _sum(self, value, d):
r, c = self.pos[value]
n = len(self.g)
ans = 0
for dr, dc in d:
nr, nc = r + dr, c + dc
if 0 <= nr < n and 0 <= nc < n:
ans += self.g[nr][nc]
return ansvar NeighborSum = function(grid) {
this.g = grid;
this.pos = new Map();
for (let i = 0; i < grid.length; i++) for (let j = 0; j < grid[0].length; j++) this.pos.set(grid[i][j], [i, j]);
};
NeighborSum.prototype.adjacentSum = function(value) { return this.sum(value, [[-1,0],[1,0],[0,-1],[0,1]]); };
NeighborSum.prototype.diagonalSum = function(value) { return this.sum(value, [[-1,-1],[-1,1],[1,-1],[1,1]]); };
NeighborSum.prototype.sum = function(value, d) {
const [r, c] = this.pos.get(value); const n = this.g.length; let ans = 0;
for (const [dr, dc] of d) { const nr = r + dr, nc = c + dc; if (nr >= 0 && nr < n && nc >= 0 && nc < n) ans += this.g[nr][nc]; }
return ans;
};
Comments