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.
inthelper(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() and0 <= nx and nx < A[0].size()) { res += A[ny][nx]; } } } } return res; } intadjacentSum(int value){ vector<int> dy{-1,0,1,0}, dx{0,-1,0,1}; returnhelper(value, dy, dx); } intdiagonalSum(int value){ vector<int> dy{-1,-1,1,1}, dx{-1,1,-1,1}; returnhelper(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); */