如何优化?
  • 板块灌水区
  • 楼主封禁用户
  • 当前回复6
  • 已保存回复7
  • 发布时间2024/10/2 18:48
  • 上次更新2024/10/2 20:36:59
查看原帖
如何优化?
973480
封禁用户楼主2024/10/2 18:48

n皇后(n<=15),输出有几种方法。 n=14,15TLE

#include<bits/stdc++.h>
using namespace std;
int n,ans=0;
struct noqueen{
	int x,y;
};
const int maxn=16*16;
noqueen queen[16];
int top=0;
bool check(int fx,int fy,int dx,int dy){
	return !(fx==dx||fy==dy||fx+fy==dx+dy||fx-fy==dx-dy);
}
void dfs(int x,int y){
	if(x==n+1){
		ans++;
		return;
	}
	top++;
	queen[top].x=x;
	queen[top].y=y;
	int fx=x+1,fy=1;
	if(fx==n+1){
		dfs(fx,fy);
	}else{
		for(fy=1;fy<=n;fy++){
        bool flag=true;
			for(int j=1;j<=top;j++){
				int dx=queen[j].x,dy=queen[j].y;
				if(!check(fx,fy,dx,dy)){
                    flag=false;
                    break;
                }
			}
			if(flag) dfs(fx,fy);
		}
	}
	queen[top].x=0;
	queen[top].y=0;
	top--;
	return;
}
int main(){
	cin >> n;
	for(int i=1;i<=n;i++) dfs(1,i);
	cout << ans;
	return 0;
}
2024/10/2 18:48
加载中...