八皇后问题

package javatask;

public class EightQueenO {
	private int[][]map;
	private int len;
	private int[]C;
	private int tol;
	public static void main(String[] args) {
		new EightQueenO().run();
	}
	public EightQueenO() {
		len = 8;
		C = new int[len];//记录当前行可放置的列
		tol = 0;
	}
	public void run() {
		search(0);
		System.out.println("total = " + tol);
	}
	public boolean isOk(int row, int col) {
			for(int j = 0; j < row; j++ ) {
				if(C[j] == col || C[j]+ j == col+row || C[j]-j == col-row) {//只需要判断当前行以前的对角线和列即可
					return false;
				}
			}
		return true;
	}
	public void search(int cur) {
		if(cur == len) {
			tol++;
			//只有到达 这里时候 才是完成了 八皇后 
			for(int i = 0; i < len; i++ ) {
				for(int j = 0; j < len; j++ ) {
					if(C[i] == j)
						System.out.print(1+" ");
					else
						System.out.print(0 +" ");
				}
				System.out.println();
			}
			System.out.println("***************");
		}
		else {
			for(int i = 0; i < len; i++ ) {
				C[cur] = i;//这里保证了 最终的值一定是构成8皇后时候的值(因为其值不断被修改直到完成所有行)
				if(isOk(cur, i)) {
				//	map[cur][i] = 1;//有的不能构成八皇后但是仍然 在末尾之前的位置满足 也被记录了
					search(cur+1);	//所以用map记录是错误的
				}
			}
		}
//			for(int i = 0; i < len; i++ ) {
//				int ok = 1;
//				C[cur] = i;
//				for(int j = 0; j < cur; j++ ) {
//					if(C[j] == C[cur]|| C[j]+ j == C[cur]+cur || C[j]-j == C[cur]-cur) {
//						ok = 0; break;
//					}
//				}
//				if(ok == 1) search(cur+1);
//			}
	}

}
中间的dfs部分可以换成   
for(int i = 0; i < len; i++ ) {
    if(isOk(cur, i)) {
     vis[cur] = i;
     search(cur+1);
     vis[cur] = 0;//保证 只有成功的时候才会被记录 然后 输出后 立刻 清零
    }
   }

C++ :

#include<iostream>
using namespace std;

const int N = 1010;
int tol;
int C[N];
int n; 
void dfs(int cur){
	if(cur == n){
		tol++;
		return ;
	}
	else for(int j = 0; j < n; ++j){
		C[cur] = j;
		bool ok = 1;
		for(int i = 0; i < cur; ++i){
			if(C[cur] == C[i] || cur-C[cur] == i-C[i] || cur + C[cur] == i+C[i]){
				ok = 0;
				break;
			}
		}
		if(ok) dfs(cur+1);
	}
}

int main()
	{
		cin >> n;
		dfs(0);
		cout << tol << endl;
		
		return 0;	
	} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值