- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 35 lines of C++ from the credited upstream file 3242.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class neighborSum {2 public:3 neighborSum(vector<vector<int>>& grid)4 : n(grid.size()), grid(grid), numToPos(n * n) {5 for (int i = 0; i < n; ++i)6 for (int j = 0; j < n; ++j)7 numToPos[grid[i][j]] = {i, j};8 }9 10 int adjacentSum(int value) {11 const auto& [i, j] = numToPos[value];12 int sum = 0;13 for (const auto& [x, y] :14 vector<pair<int, int>>{{i - 1, j}, {i + 1, j}, {i, j - 1}, {i, j + 1}})15 if (x >= 0 && x < n && y >= 0 && y < n)16 sum += grid[x][y];17 return sum;18 }19 20 int diagonalSum(int value) {21 const auto& [i, j] = numToPos[value];22 int sum = 0;23 for (const auto& [x, y] : vector<pair<int, int>>{24 {i - 1, j - 1}, {i - 1, j + 1}, {i + 1, j - 1}, {i + 1, j + 1}})25 if (x >= 0 && x < n && y >= 0 && y < n)26 sum += grid[x][y];27 return sum;28 }29 30 private:31 const int n;32 vector<vector<int>> grid;33 vector<pair<int, int>> numToPos;34};35