While loop gets terminated before condition is met when backtracking

80 Views Asked by At

I'm trying to write an iterative program that will help me palce 4 queens on a 4x4 board without them hitting each other. The problem is after looping through each position and backtracking a couple of times my main while loop that keeps looping until a solution is found gets terminated and the program ends even though the condition is not yet met.

I tried the following code:

static int[] solve(char[][] board){
    int[] position = new int[4];
    int row = 0;
    int column = 0;

    while(row < 4){
        for(boolean check; column < board.length; column++){
            System.out.println("["+row+","+column+"]");
            check = true;
            for(int queen= 0; queen < row; queen++){
                if (position[queen] == column || queen- position[queen] == row - column || queen + position[queen] == row + column) {
                    check = false;
                    break;
                }
            }
            if(check){
                position[row] = column;
                column = 0;
                row++;
            }
            if(column > 2){
                column = position[--row];
            }
        }
    }
    return position;
}

I'm currently getting the following output:

| Q | X | X | X |

| X | X | X | Q |

| X | Q | X | X |

| Q | X | X | X |

To check when exactly the while loop is getting terminated I printed the location (row and column) System.out.println("["+row+","+column+"]"); and got the following:

[0,0][1,0][1,1][1,2][2,0][2,1][2,2][2,3][1,3][2,0][2,1][3,0][3,1][3,2][3,3][2,2][2,3]

After backtracking to [2,3] the while loop ends even though my row count is still less than 4.

I was expecting the following output:

| X | Q | X | X |

| X | X | X | Q |

| Q | X | X | X |

| X | X | Q | X |

I tried the code in a different compiler and still got the same wrong output. Is there a logical mistake that I missed out?

I'm new to programming so I'm still trying to get the hang of the fundamentals.

0

There are 0 best solutions below