模拟题,需要找到之后需要判定一下边界,别越界了。
1 class NeighborSum { 2 private: 3 int n; 4 vector<vector<int>> grid; 5 vector<vector<int>> adj={{-1,0},{0,1},{1,0},{0,-1}}; 6 vector<vector<int>> diag={{-1,-1},{-1,1},{1,1},{1,-1}}; 7 public: 8 NeighborSum(vector<vector<int>>& grid) { 9 n=grid.size(); 10 this->grid=grid; 11 } 12 13 int adjacentSum(int value) { 14 int x,y; 15 for(int i=0;i<n;i++){ 16 for(int j=0;j<n;j++){ 17 if(grid[i][j]==value){ 18 x=i,y=j; 19 break; 20 } 21 } 22 } 23 int res=0; 24 for(int i=0;i<4;i++){ 25 int tx=x+adj[i][0]; 26 int ty=y+adj[i][1]; 27 if(tx<0||tx>=n||ty<0||ty>=n) 28 continue; 29 res+=grid[tx][ty]; 30 } 31 return res; 32 } 33 34 int diagonalSum(int value) { 35 int x,y; 36 for(int i=0;i<n;i++){ 37 for(int j=0;j<n;j++){ 38 if(grid[i][j]==value){ 39 x=i,y=j; 40 break; 41 } 42 } 43 } 44 int res=0; 45 for(int i=0;i<4;i++){ 46 int tx=x+diag[i][0]; 47 int ty=y+diag[i][1]; 48 if(tx<0||tx>=n||ty<0||ty>=n) 49 continue; 50 res+=grid[tx][ty]; 51 } 52 return res; 53 } 54 }; 55 56 /** 57 * Your NeighborSum object will be instantiated and called as such: 58 * NeighborSum* obj = new NeighborSum(grid); 59 * int param_1 = obj->adjacentSum(value); 60 * int param_2 = obj->diagonalSum(value); 61 */