Leetcode 3242. Design Neighbor Sum Service
Design a service that provides the sum of all neighbors of a given cell in a 2D grid. The 2D grid will be updated frequently, and for each update, you should be able to quickly recalculate the sum of neighbors for any given cell.
Implement the NeighborSumService
class:
NeighborSumService(int[][] grid)
Initializes the object with the given 2D grid.void update(int row, int col, int val)
Updates the value at the given cell (row, col)
to val
.int sum_neighbors(int row, int col)
Returns the sum of all 8 neighbors of the cell (row, col)
. If a neighbor is out of bounds, it should not be included in the sum.#include <vector>
using namespace std;
class NeighborSumService {
public:
NeighborSumService(vector<vector<int>>& grid) : grid(grid) {}
void update(int row, int col, int val) {
grid[row][col] = val;
}
int sum_neighbors(int row, int col) {
int sum = 0;
vector<pair<int, int>> directions = \{\{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
for (auto [dx, dy] : directions) {
int newRow = row + dx;
int newCol = col + dy;
if (newRow >= 0 && newRow < grid.size() && newCol >= 0 && newCol < grid[0].size()) {
sum += grid[newRow][newCol];
}
}
return sum;
}
private:
vector<vector<int>> grid;
};
(row, col)
in the grid is updated to val
.This setup ensures that updates and neighbor sum calculations are efficient, making the service responsive for frequent operations.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?