I am working on a N Queens program that will allow the user to enter Queen configuration as String. For example, when prompted, the user can enter something like Q .... Q ..... Q..Q. which when displayed in the form of a board will look like this:
Q . . . . Q . . . . . Q . . Q . Is not a solution!
This program is simple in the sense that it assumes that the user is entering valid information. I would like the main part of the program to work before I go back and add error handling.
For those who are not familiar with the N Queens puzzle, basically you have N Queens on the N x N circuit board. You have one queen in a row. A populated board is the solution if no two Queens have the same rows, columns, or diagonals.
I have successfully performed row and column checks. However, I'm at a standstill about how I can check all the diagonals. I know how to check two main diagonals, for example, in tic tac toe, but I really canβt imagine 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
java arrays 2d
Codebug
source share