力扣刷题记录
模拟
3242. 设计相邻元素求和服务
思路
这一题直接模拟即可
两层for循环找到value的位置,根据该位置将对应的数相加,如果相邻的数字 索引越界了则不加
代码
class NeighborSum:def __init__(self, grid: List[List[int]]):self.grid = griddef adjacentSum(self, value: int) -> int:row, col = 0, 0for i in range(len(self.grid)):for j in range(len(self.grid[0])):if self.grid[i][j] == value:row = i col = jbreakelse:continuebreaksum = 0if row - 1 >= 0:sum += self.grid[row-1][col]if row + 1 < len(self.grid):sum += self.grid[row+1][col]if col - 1 >= 0:sum += self.grid[row][col-1]if col + 1 < len(self.grid[0]):sum += self.grid[row][col+1]return sumdef diagonalSum(self, value: int) -> int:row, col = 0, 0for i in range(len(self.grid)):for j in range(len(self.grid[0])):if self.grid[i][j] == value:row = i col = jbreakelse:continuebreaksum = 0if row - 1 >= 0 and col - 1 >= 0:sum += self.grid[row-1][col-1]if row + 1 < len(self.grid) and col + 1 < len(self.grid[0]):sum += self.grid[row+1][col+1]if row + 1 < len(self.grid) and col - 1 >= 0:sum += self.grid[row+1][col-1]if row - 1 >= 0 and col + 1 < len(self.grid[0]):sum += self.grid[row-1][col+1]return sum# Your NeighborSum object will be instantiated and called as such:
# obj = NeighborSum(grid)
# param_1 = obj.adjacentSum(value)
# param_2 = obj.diagonalSum(value)