【发布时间】:2010-07-09 01:05:30
【问题描述】:
我正在开发一个 N Queens 程序,该程序将允许用户将 Queen 配置作为字符串输入。例如, 出现提示时,用户可能会输入类似 Q....Q....Q..Q 的内容。显示为板时的样子:
Q . . .
. Q . .
. . . Q
. . Q .
Is not a solution!
这个程序很简单,因为它假定用户将输入有效信息。我想在返回并添加错误处理之前让程序的主要部分正常工作。
对于那些不熟悉 N 皇后拼图的人来说,基本上你在 N x N 板上有 N 个皇后。你每排有一个皇后。如果没有两个皇后共享同一行、列或对角线,则填充板是一种解决方案。
我已经成功地实现了对行和列的检查。但是,我对如何检查所有对角线感到困惑。我知道如何检查两个主要对角线,就像在井字游戏中一样,但我真的无法想象如何检查所有可能的对角线?
谁能提供帮助?
这是我的代码:
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
谢谢 阅读更多:N Queens 计划需要帮助
【问题讨论】: