思路:
该方案通过构建一个字典,将每个元素值映射到其在二维数组中的坐标位置,以便快速查找。adjacentSum
方法根据指定元素的坐标,计算其上下左右相邻元素之和;diagonalSum
方法则计算该元素的四个对角线相邻元素之和。每个方法通过判断相邻坐标是否在数组边界内,确保不越界访问。初始化字典的时间复杂度为 (O(n^2)),每次查询操作为 (O(1)),满足题目要求的效率。
from typing import List, Dict, Tuple
class NeighborSum:
def __init__(self, grid: List[List[int]]):
self.grid = grid
self.n = len(grid)
# Creating a dictionary to map each value to its (row, col) position in the grid
self.value_to_position: Dict[int, Tuple[int, int]] = {}
for i in range(self.n):
for j in range(self.n):
self.value_to_position[grid[i][j]] = (i, j)
def adjacentSum(self, value: int) -> int:
if value not in self.value_to_position:
return 0
row, col = self.value_to_position[value]
adjacent_sum = 0
# Checking all four possible adjacent cells (top, left, right, bottom)
for dr, dc in [(-1, 0), (0, -1), (0, 1), (1, 0)]:
new_row, new_col = row + dr, col + dc
if 0 <= new_row < self.n and 0 <= new_col < self.n:
adjacent_sum += self.grid[new_row][new_col]
return adjacent_sum
def diagonalSum(self, value: int) -> int:
if value not in self.value_to_position:
return 0
row, col = self.value_to_position[value]
diagonal_sum = 0
# Checking all four diagonal cells (top-left, top-right, bottom-left, bottom-right)
for dr, dc in [(-1, -1), (-1, 1), (1, -1), (1, 1)]:
new_row, new_col = row + dr, col + dc
if 0 <= new_row < self.n and 0 <= new_col < self.n:
diagonal_sum += self.grid[new_row][new_col]
return diagonal_sum
标签:21,17,int,self,value,position,打卡,col,row
From: https://blog.csdn.net/weixin_53420521/article/details/143641567