八皇后问题

 

package newpackage; /** * * @author Administrator */ import java.util.*; public class Queens { // 棋盘规模 public static final int BOARD_SIZE = 8; // EMPTY赋值为0 public static final int EMPTY = 0; // QUEEN赋值为1 public static final int QUEEN = 1; private int board[][]; // chess board public Queens() { // 定义棋盘数组 board = new int[BOARD_SIZE][BOARD_SIZE]; } public void clearBoard() { // 清空棋盘 int i,j; for(i=0;i<BOARD_SIZE;i++) { for(j=0;j<BOARD_SIZE;j++) board[i][j] = EMPTY; } } // end clearBoard public void displayBoard() { // 显示棋盘 int i,j; for(i=0;i<BOARD_SIZE;i++) { for(j=0;j<BOARD_SIZE;j++) System.out.print( "/t"+board[i][j]); System.out.println("/n"); } } public boolean placeQueens(int column) { // 放置皇后 if (column > BOARD_SIZE) { return true; // 考虑每一列,直到列数大于8为止 } else { boolean queenPlaced = false; int row = 1; // number of square in column while ( !queenPlaced && (row <= BOARD_SIZE) ) { // 如果被攻击了 if (isUnderAttack(row, column)) { ++row; // 考虑下一行 } else { //放置皇后并考虑下一列 setQueen(row, column); queenPlaced = placeQueens(column+1); // 如果下一列不可能放置皇后 if (!queenPlaced) { // backtrack: 拿走上次放置的皇后,并考虑列中的下一个方块 removeQueen(row, column); ++row; } } } return queenPlaced; } } private void setQueen(int row, int column) { // 放置皇后 board[index(row)][index(column)] = QUEEN; } private void removeQueen(int row, int column) { // 取消放置 board[index(row)][index(column)] = EMPTY; } private boolean isUnderAttack(int row, int column) { // 遭受攻击的情况 int r,c; for(c=0;c<index(column);c++) //只对前column-1列检测是否被攻击 { for(r=0;r<BOARD_SIZE;r++) { if(r==index(row)&&board[r][c]==QUEEN) return true;//同行检测 if((Math.abs(r-index(row))==Math.abs(c-index(column)))&&(board[r][c]==QUEEN)) return true; //对角线检测 } } return false; } private int index(int number) { // if((number >=1) &&( number <= BOARD_SIZE)) return number-1; else return 0; } public static void main(String[] args) { System.out.println("Queens Problem"); Queens q = new Queens(); if(q.placeQueens(1)) q.displayBoard(); else System.out.println("No solution."); } }

它是一列一列考虑的,而不是一行一行的考虑

你可能感兴趣的:(八皇后问题)