build a prefix sum during construction for efficient range queries (though not strictly needed here). for neighbor sums, find the target value's position, then sum its four adjacent or four diagonal neighbors with bounds checking.
the key is safe access: check bounds before accessing grid cells to handle edge cases where neighbors might be out of bounds.
methods
- adjacentSum: sum of up, down, left, right neighbors
- diagonalSum: sum of four diagonal neighbors
- both use safeGet to handle out-of-bounds gracefully
complexity
O(mn) time to find target value, O(1) for neighbor sums. O(mn) space for grid and prefix arrays.