实现8女王使用深度优先搜索

实现8女王使用深度优先搜索

本文介绍了java:实现8女王使用深度优先搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用深度搜索来实现8个皇后,以对任何初始状态都适用于空板(在木板上没有皇后),但是如果有解决方案,如果没有解决方案,我需要它在初始状态下工作此初始状态的解决方案,它将打印没有解决方案

i am try to implement 8 queen using depth search for any initial state it work fine for empty board(no queen on the board) ,but i need it to work for initial state if there is a solution,if there is no solution for this initial state it will print there is no solution

这是我的代码:

public class depth {
   public static void main(String[] args) {
       //we create a board
       int[][] board = new int[8][8];
       board [0][0]=1;
       board [1][1]=1;
       board [2][2]=1;
       board [3][3]=1;
       board [4][4]=1;
       board [5][5]=1;
       board [6][6]=1;
       board [7][7]=1;

       eightQueen(8, board, 0, 0, false);
       System.out.println("the solution as pair");
       for(int i=0;i<board.length;i++){
           for(int j=0;j<board.length;j++)
               if(board[i][j]!=0)

               System.out.println("  ("+i+" ,"+j +")");
       }
       System.out.println("the number of node stored in memory "+count1);
   }
      public static int count1=0;
     public static void eightQueen(int N, int[][] board, int i, int j, boolean found) {

    long startTime = System.nanoTime();//time start

    if (!found) {
        if (IsValid(board, i, j)) {//check if the position is valid
            board[i][j] = 1;

            System.out.println("[Queen added at (" + i + "," + j + ")");
            count1++;
            PrintBoard(board);


            if (i == N - 1) {//check if its the last queen
                found = true;
                PrintBoard(board);
                double endTime = System.nanoTime();//end the method time

                double duration = (endTime - startTime)*Math.pow(10.0, -9.0);
                System.out.print("total Time"+"= "+duration+"\n");
            }
            //call the next step
            eightQueen(N, board, i + 1, 0, found);
        } else {

            //if the position is not valid & if reach the last row we backtracking
            while (j >= N - 1) {
                int[] a = Backmethod(board, i, j);
                i = a[0];
                j = a[1];

                System.out.println("back at (" + i + "," + j + ")");
                PrintBoard(board);
            }
            //we do the next call
            eightQueen(N, board, i, j + 1, false);
        }
    }

}

public static int[] Backmethod(int[][] board, int i, int j) {
    int[] a = new int[2];
    for (int x = i; x >= 0; x--) {
        for (int y = j; y >= 0; y--) {
            //search for the last queen
            if (board[x][y] != 0) {
                //deletes the last queen and returns the position
                board[x][y] = 0;
                a[0] = x;
                a[1] = y;
                return a;
            }
        }
    }
    return a;
}

public static boolean IsValid(int[][] board, int i, int j) {

    int x;
    //check the queens in column
    for (x = 0; x < board.length; x++) {
        if (board[i][x] != 0) {
            return false;
        }
    }
    //check the queens in row
    for (x = 0; x < board.length; x++) {
        if (board[x][j] != 0) {
            return false;
        }
    }
    //check the queens in the diagonals
    if (!SafeDiag(board, i, j)) {
        return false;
    }
    return true;
}

public static boolean SafeDiag(int[][] board, int i, int j) {

    int xx = i;
    int yy = j;
    while (yy >= 0 && xx >= 0 && xx < board.length && yy < board.length) {
        if (board[xx][yy] != 0) {
            return false;
        }
        yy++;
        xx++;
    }
    xx = i;
    yy = j;
    while (yy >= 0 && xx >= 0 && xx < board.length && yy < board.length) {
        if (board[xx][yy] != 0) {
            return false;
        }
        yy--;
        xx--;
    }
    xx = i;
    yy = j;
    while (yy >= 0 && xx >= 0 && xx < board.length && yy < board.length) {
        if (board[xx][yy] != 0) {
            return false;
        }
        yy--;
        xx++;
    }
    xx = i;
    yy = j;
    while (yy >= 0 && xx >= 0 && xx < board.length && yy < board.length) {
        if (board[xx][yy] != 0) {
            return false;
        }
        yy++;
        xx--;
    }
    return true;
}
public static void PrintBoard(int[][] board) {
    System.out.print(" ");
    for (int j = 0; j < board.length; j++) {
        System.out.print(j);
    }
    System.out.print("\n");
    for (int i = 0; i < board.length; i++) {
        System.out.print(i);
        for (int j = 0; j < board.length; j++) {
            if (board[i][j] == 0) {
                System.out.print(" ");
            } else {
                System.out.print("Q");
            }
        }
        System.out.print("\n");
    }
}


}

例如,对于此初始状态,它会给我以下错误:

for example for this initial state it give me the following error:

Exception in thread "main" java.lang.StackOverflowError

我被困住了,我认为错误是该方法如何解决这个问题的无限呼吁.

i am stuck, i think the error is infinite call for the method how to solve this problem.

任何想法都会有所帮助,谢谢.

any idea will be helpful,thanks in advance.

注意:宽泛是二维数组,当我放入(1)时,它表示此时是女王.

note:the broad is two dimensional array,when i put (1) it means there queen at this point.

note2:我们将初始状态设置为以下状态:

note2:we i put the initial state as the following it work:

       board [0][0]=1;
       board [1][1]=1;
       board [2][2]=1;
       board [3][3]=1;
       board [4][4]=1;
       board [5][5]=1;
       board [6][6]=1;
       board [7][1]=1;

推荐答案

要添加到@StephenC的答案中:

To add to @StephenC's answer:

这是一段复杂的代码,特别是如果您没有Java编程经验的话.

This is a heck of a complicated piece of code, especially if you're not experienced in programming Java.

我执行了您的代码,并一遍又一遍地(一遍又一遍)输出它

I executed your code, and it outputs this over and over and over and over (and over)

back at (0,0)
 01234567
0
1 Q
2  Q
3   Q
4    Q
5     Q
6      Q
7       Q
back at (0,0)

然后崩溃

Exception in thread "main" java.lang.StackOverflowError
    at java.nio.Buffer.<init>(Unknown Source)
    ...
    at java.io.PrintStream.print(Unknown Source)
    at java.io.PrintStream.println(Unknown Source)
    at Depth.eightQueen(Depth.java:56)
    at Depth.eightQueen(Depth.java:60)
    at Depth.eightQueen(Depth.java:60)
    at Depth.eightQueen(Depth.java:60)
    at Depth.eightQueen(Depth.java:60)
    ...

我的第一个直觉总是添加一些System.out.println(...)来找出问题所在,但这在这里不起作用.

My first instinct is always to add some System.out.println(...)s to figure out where stuff is going wrong, but that won't work here.

我唯一看到的两个选择是

The only two options I see are to

  • 熟悉调试器并使用它来逐步分析其为何永不停止循环
  • 把它弄碎!您如何希望在不将其分解为可消化的大块的情况下处理此类大问题?

更不用说 8皇后的概念很复杂.

Not to mention that the concept of 8-queens is complicated to begin with.

进一步思考:

System.out.println()在当前实现中没有用,因为存在无限的输出.在这里,调试器是更好的解决方案,但是另一种选择是以某种方式限制您的输出.例如,在顶部创建一个计数器

System.out.println()s are not useful as currently implemented, because there's infinite output. A debugger is the better solution here, but another option is to somehow limit your output. For example, create a counter at the top

private static final int iITERATIONS = 0;

,而不是

System.out.println("[ANUMBERFORTRACING]: ... USEFUL INFORMATION ...")

使用

conditionalSDO((iITERATIONS < 5), "[ANUMBERFORTRACING]: ... USEFUL INFORMATION");

这是函数:

private static final void conditionalSDO(boolean b_condition, String s_message)  {
   if(b_condition)  {
       System.out.println(s_message);
   }
}

另一种选择是不限制输出,而是将其写入文件.

Another alternative is to not limit the output, but to write it to a file.

我希望这些信息对您有所帮助.

I hope this information helps you.

(注意:我编辑了OP的代码以使其可编译.)

(Note: I edited the OP's code to be compilable.)

这篇关于java:实现8女王使用深度优先搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:45