考考大家,一个我想了好久没想懂的问题,萌新求助
查看原帖
考考大家,一个我想了好久没想懂的问题,萌新求助
138189
cooronx楼主2021/11/24 23:09
#include<iostream>
#include<cmath>
using namespace std;
int n;
int tot;
int col[104];
bool check(int v, int k) {
	for (int i = 1; i <= k; ++i) {
		if (col[i] == v || abs(col[i] - v) == abs(i - k)) {
			return false;
		}
	}
	return true;
}
void dfs(int step) {
	if (step == n+1) {
		++tot;
		if (tot > 3) {
			return;
		}
		else {
			for (int i = 1; i <= n; ++i) {
				cout << col[i] << " ";
			}
			cout << endl;
			return;
		}
	}
	else {
		for (int i = 1; i <= n; ++i) {
			if (check(i, step)) {
				col[step] = i;
				dfs(step + 1);
				//col[step] = 0;
			}
		}
	}
}
int main() {
	cin >> n;
	dfs(1);
	cout << tot << endl;
	return 0;
}

就是这一句

col[step] = 0;

加上就可以按顺序,不加就不能。。。

确实有点想不懂

2021/11/24 23:09
加载中...