International chess
Eight queens problem is an old and well-known problems, is a typical case of backtracking algorithms. The problem is an international chess player Max Bethel presented in 1848: placed on the international chess 8 × 8 grid of eight Queens, it can not attack each other, that is, any two queens can not be in the same line, on the same row or the same slash and asked how many pendulum method.
public class _8Queen { // backtracking, violent solution 8 queens Private static int Ways = 0 ; // returns the number of Solution public static int f8queen () { int [] [] = Board new new int [8] [8 ]; ways = 0; p_f8queen(board, 0); return ways; } private static void p_f8queen(int[][] board, int row) { if (row > 7) { ways++; printBoard (Board); // the last line of exhaustive complete, output chessboard return ; } for ( int COL = 0; COL <. 8; COL ++ ) { IF (Check (Board, Row, COL)) { // detect whether the rules Board [Row] [COL] =. 1; // put Queen pieces p_f8queen (board , row +. 1); // the next line Board [row] [COL] = 0; // Clear } } } private static void printBoard(int[][] board) { for (int row = 0; row < 8; row++) { for (int col = 0; col < 8; col++) { if (board[row][col] != 1) Of System.out.print ( '.'); // a checkerboard grid blank. The else of System.out.print ( 'Q'); // Q Queen pieces } System.out.println(); } System.out.println("=============="); } private static boolean check(int[][] board, int row, int col) { for (int tmprow = row - 1; tmprow >= 0; tmprow--) { int l = col - (row - tmprow); int r = col + (row - tmprow); if (l > -1 && board[tmprow][l] != 0) //左上角线 return false; if (r < 8 && board[tmprow][r] != 0) //右上角线 return false; if(Board [tmprow] [COL] = 0!) // top line return to false ; } return true; } public static void main(String[] ar) { System.out.println(f8queen()); } }
Export
Q....... ....Q... .......Q .....Q.. ..Q..... ......Q. .Q...... ...Q.... ============== . . . . . . . . . (Too much .... omitted) ============== .......Q ...Q.... Q....... ..Q..... .....Q.. .Q...... ......Q. ....Q... ============== 92
We can see out of the 92 kinds of exhaustive
In fact, there is a solution based on graph theory