3242. 设计相邻元素求和服务
为保证权益,题目请参考 3242. 设计相邻元素求和服务(From LeetCode).
解决方案1
Python
python
from typing import List
class NeighborSum:
def __init__(self, grid: List[List[int]]):
self.grid = grid
self.re_map = dict()
for row_idx, row in enumerate(self.grid):
for col_idx, x in enumerate(row):
self.re_map[x] = (row_idx, col_idx)
def adjacentSum(self, value: int) -> int:
row_idx, col_idx = self.re_map[value]
ans = 0
ans += self.grid[row_idx - 1][col_idx] if row_idx != 0 else 0
ans += self.grid[row_idx + 1][col_idx] if row_idx != len(self.grid) - 1 else 0
ans += self.grid[row_idx][col_idx - 1] if col_idx != 0 else 0
ans += (
self.grid[row_idx][col_idx + 1] if col_idx != len(self.grid[0]) - 1 else 0
)
return ans
def diagonalSum(self, value: int) -> int:
row_idx, col_idx = self.re_map[value]
ans = 0
ans += (
self.grid[row_idx - 1][col_idx - 1] if row_idx != 0 and col_idx != 0 else 0
)
ans += (
self.grid[row_idx + 1][col_idx - 1]
if row_idx != len(self.grid) - 1 and col_idx != 0
else 0
)
ans += (
self.grid[row_idx + 1][col_idx + 1]
if row_idx != len(self.grid) - 1 and col_idx != len(self.grid[0]) - 1
else 0
)
ans += (
self.grid[row_idx - 1][col_idx + 1]
if row_idx != 0 and col_idx != len(self.grid[0]) - 1
else 0
)
return ans
# Your NeighborSum object will be instantiated and called as such:
# obj = NeighborSum(grid)
# param_1 = obj.adjacentSum(value)
# param_2 = obj.diagonalSum(value)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52