解决了8个皇后

时间:2013-12-01 16:24:36

标签: java breadth-first-search

我要做的是解决8皇后问题以产生1个解决方案。我试图使用BFS这样做。以下是我到目前为止所做的工作。我认为除了我无法开始工作的最终方法()之外,我的所有功能/方法都是正确的。如果我编译并运行以下代码,我会得到一个NullPointerException。想知道如何克服这个问题并让它发挥作用。

public class Queens 
{
//Number of rows or columns

public int[][] board; // creating a two dimentional array

public int Queen = 1;
//Indicate an empty square
public boolean Conflict(int row, int col) 
{
    int[ ][ ]board = new int[8][8];
    int row1;
    int col1;
    boolean flg = false;
    row1 = row;
    col1 = col;
    // check right
    while(row1<8)
    {
        if(board[row1][col1]==1)
        {
            row1++;

        }
    }

//check left
    while(row1>=0)
    {
        if(board[row1][col1]==1)
        {
            row1--;
        }
    }
// check down
    while(col1<8)
    {
        if(board[row1][col1]==1)
        {
           col1++;
        }
    }

// check up 
    while(col1>1)
    {

        if (board[row1][col1]==1)
        {
            col1--;
        }

    }
//dia-down-right
while(row1<8 && col1<8){
    if(board[row1][col1]==1)
    {
        row1++;
        col1++;
    }
}

//dia-down-left
while(row1>=0 && col1<8){
    if(board[row1][col1]==1)
    row1--;
    col1++;
}   
//dia-up-left
while(row1>=0 && col1>=0){
    if(board[row1][col1]==1)
    row1--;
    col1--;
}

//dia-up-right
while(row1<8 && col1>=0){
    if(board[row1][col1]==1)
    row1++;
    col1--;
}       
    return flg;



}

public void disp()
{
int i,j;
for(i=0;i<8;i++)
{
    for(j=0;j<8;j++)
    {
        System.out.println(board[j][i]);
    }
                //System.out.println(board[j][i]);
}
}

public void init()
{
int i,j;
for(i=0;i<8;i++)
{
    for(j=0;j<8;j++)
    {
        board[i][j] = 0;
    }
}
}

public void placeQueen(int x,int y)
{
board[x][y]= Queen;
Queen++;
}

public void method()
{


int x,y;
int initx=0;
int inity=0;

Queen=0;
init();

placeQueen(initx,inity);
y=0;
while(y<8)
{
    x=0;
    while(x<8)
    {
        if(!Conflict(x,y))
        {
            placeQueen(x,y);
            x++;
        }
    }
    y++;
}
if(Queen<8){
    if(initx+1<8)
    {
        initx++;
        disp();
    }
    else
    {
        initx=0;
        if(inity+1<8)
        {
            inity++;
        }
        else{
            disp();
            }
    }


}

}   
public static void main(String[] args) 
{
Queens Main = new Queens();
Main.method();

}
}

1 个答案:

答案 0 :(得分:1)

您需要在第5行初始化电路板,否则在初始板中调用时:

board[i][j] = 0;

board [i] [j]为null

public class Queens
{
//Number of rows or columns

    public int[][] board = new int[8][8]; // creating a two dimentional array

    public int Queen = 1;