Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need Help With N Queens Program ( checking diagonals )

Tags:

java

arrays

2d

I'm working on an N Queens program that will allow the user to enter a Queen configuration as a String. For example, when prompted, the user might enter something like Q....Q.....Q..Q. which when displayed as a board would look like:

Q . . .
. Q . .
. . . Q
. . Q .
Is not a solution!

This program is simple in that it assumes that the user will enter valid information. I would like to get the main part of the program working before I go back and add error handling.

For those not familiar with the N Queens puzzle, basically you have N Queens on an N x N board. You have one Queen per row. A populated board is a solution if no two Queens share the same row, column or diagonal.

I have successfully implemented checks for the rows and columns. However, I am stumped as to how I can check all the diagonals. I know how to check the two main diagonals, like in tic tac toe, but I really can't visualize how I can check all possible diagonals?

Can anyone offer help?

Here is my code:

import java.util.Scanner;
public class NQueens {


    public static void main(String[] args) {

        Scanner sc = new Scanner( System.in );
        int qCount;
        boolean solution = true;


        System.out.println( "Enter the String to test:" );
        board = sc.nextLine();

        int boardLen = board.length();
        int maxDim = (int) Math.sqrt(boardLen);
        char[][] gameBoard = new char[maxDim][maxDim];


        int counter = 0;
        for ( int i = 0; i < maxDim; i++ )
        {
            for ( int j = 0; j < maxDim; j++ )
            {
                gameBoard[ i ][ j ] = board.charAt( counter );
                counter++;
            }

        }


        System.out.println("");
        System.out.println("");




    //check rows     

    for ( int i = 0; i < maxDim; i++ )
    {
        int queenCount = 0;

        for ( int j = 0; j < maxDim; j++ )
        {
            if ( gameBoard[ i ][ j ] == 'Q' )
            {
                queenCount++;


                if ( queenCount > 1 )
                {
                    solution = false;
                    break;

                }


            }


        }

    }


    // check columns

    for ( int i = 0; i < maxDim; i++ )
    {
        int queenCount = 0;

        for ( int j = 0; j < maxDim; j++ )
        {
            if ( gameBoard[ j ][ i ] == 'Q' )
            {
                queenCount++;

                if ( queenCount > 1 )
                {
                    solution = false;
                    break;
                }
            }
        }
    }


    // print the board

    for( int i = 0; i < maxDim; i++ )
    {
        for ( int j = 0; j < maxDim; j++ )
        {
            System.out.print( gameBoard[ i ][ j ] + " " );
        }

        System.out.println();

    }

    // print whether or not the placement of queens is a solution
    if ( solution )
    {
        System.out.println( "Is a solution!" );

    }

    else
    {
        System.out.println( "Is not a solution!" );

    }

    }//end main

}//end class

Thanks Read more: Need Help With N Queens Program

like image 933
Codebug Avatar asked Jul 09 '10 01:07

Codebug


People also ask

What is the best way to solve n queens?

1) Start in the leftmost column 2) If all queens are placed return true 3) Try all rows in the current column. Do following for every tried row. a) If the queen can be placed safely in this row then mark this [row, column] as part of the solution and recursively check if placing queen here leads to a solution.

What will be the condition need to test for queens to be on same diagonal in n queens problem?

First, if two queens lie on the same diagonal, one of the following conditions must be true: The row number plus the column number for each of the two queens are equal. In other words, queens(j) + j has the same value for two different indices j .

Which algorithm is used to solve n queens?

Genetic Algorithm gives the optimal solution depending on the nature of the fitness function and also on the structure of the algorithm used. Here, Genetic Algorithm is used to solve the N Queens Problem.

Why is the two queen problem not solvable?

The N-Queen problem states as consider a n x n chessboard on which we have to place n queens so that no two queens attack each other by being in the same row or in the same column or on the same diagonal. 2 – Queen's problem is not solvable because 2 – Queens can be placed on 2 x 2 chess board as shown in figure 9.


2 Answers

I don't think you want to check all the diagonals, but you can check all the queens instead. You can check to see if two queens are on the same diagonal by checking the differences between the rows and columns of the two Qs. If the differences are the same, they're on the same diagonal. (Basically, if the slope of the line between the two queens is +-1, they're on the same diagonal.)

For example, say you have two queens Q1 and Q2. Calculate the absolute value of the differences in their rows and columns.

deltaRow = abs(Q1 row - Q2 row)
deltaCol = abs(Q1 col - Q2 col)

If deltaRow == deltaCol, the queens are on the same diagonal.

Just do that for all N queens.

like image 177
Bill the Lizard Avatar answered Nov 15 '22 15:11

Bill the Lizard


We can say that the queens are on the same diagonal if the slope of the line connecting the 2 queens is either 1 or -1.

Let q1 and q2 be data structures holding the x and y positions of each queen:

xDistance = q1.x - q2.x
yDistance = q1.y - q2.y
slope = xDistance / yDistance

So if (Math.abs(slope) == 1) then they are on the same diagonal.

like image 44
A. Sallai Avatar answered Nov 15 '22 17:11

A. Sallai