求助!!最后一个点TLE......输入数据:13
  • 板块学术版
  • 楼主Neven
  • 当前回复3
  • 已保存回复3
  • 发布时间2022/8/3 22:23
  • 上次更新2023/10/27 17:08:39
查看原帖
求助!!最后一个点TLE......输入数据:13
670998
Neven楼主2022/8/3 22:23

源码:

#include<bits/stdc++.h>
using namespace std;
int n, a[15][15], cnt;
int dx[] = {0, -1, 0, 1},
	dy[] = {1, 0, -1, 0};
void print(){
	for(int i = 1; i <= n; i++){
		for(int j = 1; j <= n; j++){
			if(a[i][j] == 1){
				cout << j << " ";
			}
		}
	}
	cout << endl;
}
bool check(int n, int x, int y){
	//检查列 
	for(int i = 1; i <= n; i++){
		if(a[i][y] == 1) return false;
	}
	//检查左上-右下 
	for(int i = 1; i <= n; i++){
		for(int j = 1; j <= n; j++){
			if(i - j == x - y){
				if(a[i][j] == 1) return false;
			}
		}
	}
	//检查右上-左下 
	for(int i = 1; i <= n; i++){
		for(int j = 1; j <= n; j++){
			if(i + j == x + y){
				if(a[i][j] == 1) return false;
			}
		}
	}
	return true;
}
void dfs(int n, int r){
	if(r == n + 1){
		cnt++;
		if(cnt <= 3){
			print();
		}
		return;
	}
	for(int i = 1; i <= n; i++){
		if(check(n, r, i)){
			a[r][i] = 1;
			dfs(n, r + 1);
			a[r][i] = 0;
		}
	}
}
int main(){
	cin >> n;
	dfs(n, 1);
	cout << cnt << endl; 
	return 0;
}
2022/8/3 22:23
加载中...