[LeetCode] Design Neighbor Sum Service

3242. Design Neighbor Sum Service

You are given a n x n 2D array grid containing distinct elements in the range [0, n2 - 1].

Implement the neighborSum class:

  • neighborSum(int [][]grid) initializes the object.
  • int adjacentSum(int value) returns the sum of elements which are adjacent neighbors of value, that is either to the top, left, right, or bottom of value in grid.
  • int diagonalSum(int value) returns the sum of elements which are diagonal neighbors of value, that is either to the top-left, top-right, bottom-left, or bottom-right of value in grid.
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
class neighborSum {
vector<vector<int>> A;
public:
neighborSum(vector<vector<int>>& grid) {
A = grid;
}

int helper(int x, vector<int>& dy, vector<int>& dx) {
int res = 0;
for(int i = 0; i < A.size(); i++) {
for(int j = 0; j < A[i].size(); j++) {
if(A[i][j] != x) continue;
for(int k = 0; k < 4; k++) {
int ny = i + dy[k], nx = j + dx[k];
if(0 <= ny and ny < A.size() and 0 <= nx and nx < A[0].size()) {
res += A[ny][nx];
}
}
}
}
return res;
}

int adjacentSum(int value) {
vector<int> dy{-1,0,1,0}, dx{0,-1,0,1};
return helper(value, dy, dx);
}

int diagonalSum(int value) {
vector<int> dy{-1,-1,1,1}, dx{-1,1,-1,1};
return helper(value, dy, dx);
}
};

/**
* Your neighborSum object will be instantiated and called as such:
* neighborSum* obj = new neighborSum(grid);
* int param_1 = obj->adjacentSum(value);
* int param_2 = obj->diagonalSum(value);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/08/04/PS/LeetCode/design-neighbor-sum-service/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.