There are couple obvious "style reasons" for the "out of bounds" logic errors:
One is the use of use of 1D array for the logical 2D matrix, which requires distracting index calculations.
The other is the use of 'i' and 'j'. Easy to write, but less expressive than for example 'row' and 'col'. The better the names show the purpose, the easier it is to spot logical errors.