这是我的搜索第一题,满怀欣喜交题就卡死了!
查看原帖
这是我的搜索第一题,满怀欣喜交题就卡死了!
190100
EPFitwin楼主2021/3/26 16:00

我用x、y、sum(皇后总数)进行dfs,每次让y右移,当y超出范围时换到下一行。 最后用string记录每个合法的答案,sort一下并输出。 不知道怎么会RE和TLE呢?求解答!

#include <iostream>
#include <set>
#include <map>
#include <queue>
#include <vector>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long LL;
const int MAXN = 200;
int n, ans;
int mapp[MAXN][MAXN];
bool row[MAXN], col[MAXN], dg[MAXN], udg[MAXN];
string str[MAXN];

void dfs(int x, int y, int sum) {
//	cout << x << " " << y << endl;
	if(y == n+1) {
		y = 1, x ++;
	}
	if(x == n+1) {
		if(sum == n) {
			for(int i = 1; i <= n; i++) {
				for(int j = 1; j <= n; j++) {
					if(mapp[i][j] == 1) {
						str[ans] += j + '0';
					}
				}
			}
			ans++;
		}
		return;
	}
	// 不放 
	dfs(x, y+1, sum);
	// 放 
	if(!row[x] && !col[y] && !dg[y-x+n] && !udg[x+y]) {
		mapp[x][y] = 1;
		row[x] = col[y] = dg[y-x+n] = udg[x+y] = 1;
		dfs(x, y+1, sum+1);
		mapp[x][y] = 0;
		row[x] = col[y] = dg[y-x+n] = udg[x+y] = 0;
	}
}

int main() {
	cin >> n;
	dfs(1, 1, 0);
	sort(str, str + ans);
	for(int i = 0; i < 3; i++) {
		for(int j = 0; j < n; j++) {
			cout << str[i][j] << " ";
		}
		cout << endl;
	}
	cout << ans;
	return 0;
}


2021/3/26 16:00
加载中...