Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

artificial intelligence - java:implement 8 queen using depth first search

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

Here is my code:

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+"
");
            }
            //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("
");
    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("
");
    }
}


}

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.

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

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; 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You asked for ideas on how to solve it (as distinct from solutions!) so, here's a couple of hints:

Hint #1:

If you get a StackOverflowError in a recursive program it can mean one of two things:

  • your problem is too "deep", OR
  • you've got a bug in your code that is causing it to recurse infinitely.

In this case, the depth of the problem is small (8), so this must be a recursion bug.

Hint #2:

If you examine the stack trace, you will see the method names and line numbers for each of the calls in the stack. This ... and some thought ... should help you figure out the pattern of recursion in your code (as implemented!).

Hint #3:

Use a debugger Luke ...

Hint #4:

If you want other people to read your code, pay more attention to style. Your indentation is messed up in the most important method, and you have committed the (IMO) unforgivable sin of ignoring the Java style rules for identifiers. A method name MUST start with a lowercase letter, and a class name MUST start with an uppercase letter.

(I stopped reading your code very quickly ... on principle.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...