2d array and index looping

Hi everyone,
I have a 2d array of cells (like a chessboard), the problem is that it seems that it keeps counting the indexes despite the edges of the grid.
This is happening in vertical but not in horizontal.
I don’t understand why is counting that way and how to avoid this.

here is the code

for (int i = 0; i<ROW; i++) {
        for (int j = 0; j<COL; j++) {
            
            if (cells[i][j].rect.inside(x, y)) {
             
                if (cells[i][j].getPossible() == true && cells[i][j].cellval == " ") {
                    clickCounter++;
                    refreshPossible();

                    cells[i][j].setActive(true);
                    cells[i][j].cellval = ofToString(clickCounter);
                    <img src="/uploads/default/original/2X/e/e1e139b0b69f30a69a1636c903f14179abfe9303.png" width="300" height="500"><img src="/uploads/default/original/2X/4/4876d1c1b3909c9dc1bc4e3f1505f34350c5444e.png" width="296" height="499">
                    cells[i][j-3].setPossible(true);
                    cells[i][j+3].setPossible(true);

            }
            
        }
    }
}

I am attaching the images. The yellow cells are the one I am referring about (index +3 and -3)
any idea about this?
thanks.

Hi,
What do you expect to happen in your second example?
I guess you want only a cell to turn yellow, the one at j+3.
You have to check the bounds of the array before adressing a cell.
For example:

// Only modify the cell i,j-3 if j-3 is a correct indice
if ( j-3 >=0 ) cells[i][j-3].setPossible(true);
// Only modify the cell i,j+3 if j+3 is a correct indice
if ( j+3 < COL ) cells[i][j-3].setPossible(true);

Using cells[i][j] in your code, without being sure that
0 <= i < ROW
and 0 <= j < COL
can produce unexpected behaviour, and crash the application.

Hello @lilive
sorry for the super late reply and thanks for the feedback. YEs you are correct I would expect just one tile to light up in the second jpg. I thought to condition everything like you suggested. it works.
Still I don’t understand why without constraints this issue is present for the columns and not for the rows.
(i+3 and i-3 where not breaking…)
It is just a curiosity at this stage, as the code seems to work nicely.

THanks!