首页 > 代码库 > 八皇后解法(回溯法)

八皇后解法(回溯法)

package com.company;

/**
* Created by Administrator on 2016/9/15.
*/
public class EigthQueue {
private static int N = 8;
private int count = 0; // 总方案数
private int[] flag = {-1, -1, -1, -1, -1, -1, -1, -1};
//回溯法递归实现八皇后问题
//输出棋盘
private void printChessboard(){
int [][]chessboard = new int[N][N];
for ( int i=0; i<N; i++) {
chessboard[i][flag[i]] = 1;
}
for ( int i=0; i<N; i++) {
for ( int j=0; j<N; j++) {
System.out.print(String.format("%d ", chessboard[i][j]));
}
System.out.println();
}
}
private boolean checkQueen(int p){
boolean flag_t = true;
int pv = flag[p];
if ( p==0) {
return flag_t;
}
p--;
for ( int i=1; p>=0; p--, i++) {
if ( flag[p]==pv || flag[p]==pv-i || flag[p]==pv+i) {
flag_t = false;
}
}
return flag_t;
}
public void eightQueen(int p){
for ( int i=0; i<N; i++) {
flag[p] = i;
if ( checkQueen( p)==true && p==7) {
count++;
System.out.println("第" + count + "种:");
printChessboard( );
}
else if ( checkQueen( p ) == true){
eightQueen(p+1);
}
}
}

public static void main(String[]args){
// 记录开始时间
long a=System.currentTimeMillis();
EigthQueue eigthQueue = new EigthQueue();
eigthQueue.eightQueen(0);
// 记录结束时间
System.out.println("\r<br>执行耗时 : "+(System.currentTimeMillis()-a)/1000f+" 秒 ");
}
}

八皇后解法(回溯法)