n-皇后

public class Main{
    public static void main( String [] args ){
        NQueens nqueens = new NQueens(5);
        nqueens.getAllSolutionVector();
    }
}

class NQueens {
	//表示n*n的棋盘
	private Integer n = null;
	//存放解向量
	private Integer [] solutionVector = null;
	//构造函数
	NQueens(){}
	NQueens( int n){
		this.n = n;
		this.solutionVector = new Integer[this.n];
		for( int i = 0; i < this.n; i++) {
			this.solutionVector[i] = Integer.MAX_VALUE ;
		}
	}
	/**
	 * 判断第queenIndex个皇后放在positon列是否可行
	 * @param queenIndex 第queenIndex个皇后,第一个皇后queenIndex=0,
	 * @param positon 皇后要放在棋盘的第positon列。棋盘行数列数从0开始
	 * @return
	 */
	private boolean feasible( int queenIndex, int positon) {
		//由参数queenIndex,可知,前面queenIndex-1个皇后已经找好了位置
		for( int i = 0; i < queenIndex; i++) {
			//不能放在同列,不能放在对角线上
			if( positon==this.solutionVector[i] || Math.abs( queenIndex - i ) == Math.abs( positon-this.solutionVector[i] ))
				return false;
		}
		return true;
	}
	//得到所有的解向量并输出
	private void getAllSolutionVector( int queenIndex) {
		if( queenIndex == this.n ) {
			for( int i = 0; i<this.n; i++) {
				System.out.println(this.solutionVector[i]);
			}
			System.out.println("===========================================");
		}
		for( int i = 0; i < this.n; i++ ) {
			if( feasible(queenIndex,i)) {
				this.solutionVector[queenIndex]	 = i;
				this.getAllSolutionVector(queenIndex+1);
			}		
		}
	}
	public void getAllSolutionVector() {
		this.getAllSolutionVector(0);
	}
	//只获取第一个个解向量
	private boolean getFirstSolutionVector( int queenIndex) {
		boolean flag = false;
		if( queenIndex == this.n ) {
			for( int i = 0; i<this.n; i++) {
				System.out.println(this.solutionVector[i]);
			}
			System.out.println("===========================================");
			return true;
		}
		for( int i = 0; i < this.n && flag == false; i++ ) {
			if( feasible(queenIndex,i)) {
				this.solutionVector[queenIndex]	 = i;
				flag = this.getFirstSolutionVector(queenIndex+1);
			}		
		}
		return flag;
	}
	public void getFirstSolutionVector() {
		this.getFirstSolutionVector(0);
	}
}

 

点赞