javaarraysmultidimensional-arrayindexingn-queens

Index is out of bounds checking diagonal path in n-queens


I have to write a program for class to test a 2D-Array. It's the "the 8 queens problem". All we have to do is write the code to test weather a given 2D-Array has a valid positioning for all eight queens, meaning:

  1. Only one queen per row.

  2. Only one queen per column.

  3. Only one queen for every diagonal path.

The problem I have is with the diagonal iteration. I get an Index 8 out of bounds for length 8 error.

int gitter [][] // name for the 2D-Array
public static boolean gitterIstRichtig = true; // this is to check if conditions are met

for (row = 0; row <= gitter.length - 1; row++){
    queens = 0;

    for (column = 0; column <= gitter[0].length - 1; column++)
    {
        
        queens += gitter[row][column];
        
        if ((gitter[row][column] == 1) && ((row + 1) <= gitter.length - 1))
        {
            if ((column + 1) <= gitter[0].length - 1)
            {
                int n = 1;
                while ((column + n) <= gitter[0].length - 1)
                {
                    if ((gitter[row + n][column + n] == 1)) // HERE IS WHERE THE ERROR POINTS TO
                    {
                        gitterIstRichtig = false;
                    }
                    n++;
                }
            }
            if ((column - 1) >= 0)
            {
                int n = 1;
                while ((column - n) >= 0)
                {
                    if ((gitter[row + n][column - n] == 1)) // HERE IS WHERE THE ERROR POINTS TO                            
                    {
                        gitterIstRichtig = false;
                    }
                    n++;
                }
            }
        }
    }
}



Solution

  • your code looks complicated. The mixing between English and German variables is confusing. columns = Spalten, gitter = grid

    Anyway... I assume the problem is in gitter[row + n][column + n]. You check if column+n is in the valid index range but you do not check, if row + n is a valid index.