算法模版之八皇后问题

问题描述:

一个8X8的棋盘上,每一行放一个皇后棋子,要求每一列,每一写对角线只能有一个皇后,求有多少种摆法。


解题方法:回溯深搜,所有的位置都摆一次,符合条件则输出。


代码如下

class Main { 
	static int count;
	static int z_y []=new int [16];//从左到右一共有16条对角线
	static int y_z []=new int [16];//从右到左一共有16条对角线
	static int lie []=new int [8];//一共有8列
	public static void main(String[] args) {
		f(0);
		System.out.println(count);
	}
	static void f(int n) {//n表示摆第几个棋子
		if(n==8) {
			count++;
			return;
		}
		else {
			for(int i=0;i<8;i++) {//i表示当前棋子摆在当前行的第几个位置
				if(lie[i]==0 && z_y[i+n]==0 && y_z[i+7-n]==0) {//判断是否在对角线和同一列中已经有过棋子
					{lie[i]=1;z_y[i+n]=1;y_z[i+7-n]=1;}
					f(n+1);
					{lie[i]=0;z_y[i+n]=0;y_z[i+7-n]=0;}//,当前位置不摆,回溯
				}
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/habewow/article/details/80424981