Stateful Neuron Matrix Update
Problem statement
A matrix cell with value 0 is a firing neuron; a positive value is non-firing. Update every cell simultaneously using its up to eight surrounding neighbors.
- A firing neuron becomes
6when exactly three neighbors are firing; otherwise it stays0. - A non-firing neuron loses
2when zero or one neighbor is firing. - It loses
1when more than three neighbors are firing. - With exactly two or three firing neighbors, a non-firing neuron is unchanged.
- Values never fall below zero.
Return the matrix after one simultaneous update.
Function
updateNeuronMatrix(grid: int[][]) → int[][]Examples
Example 1
grid = [[1,0,1],[0,5,0],[1,1,1]]return = [[1,0,1],[0,5,0],[0,1,0]]The center has exactly three firing neighbors and, as a non-firing value, remains 5. Each bottom corner has one firing neighbor and decreases to 0.
Example 2
grid = [[5,5],[5,5]]return = [[3,3],[3,3]]Every neuron has zero firing neighbors, so each value decreases by 2.
Example 3
grid = [[0,0],[0,0]]return = [[6,6],[6,6]]Each corner has exactly three neighbors and all three are firing.
Constraints
1 <= grid.length, grid[i].length <= 1000.- All rows have equal length.
0 <= grid[i][j] <= 1000000000.