AcWing 1432. 棋盘挑战
原题链接
中等
作者:
LingYunX
,
2021-02-24 22:01:17
,
所有人可见
,
阅读 264
1. 记录下棋盘的内容 慢一些
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 15, M = 30;
char g[N][N];
// 直接记录答案也行
int path[N];
bool col[N], dg[M], ndg[M];
int n;
int num;
void dfs(int r){
if (r == n + 1){
num ++ ;
if (num <= 3){
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= n; j ++ )
if (g[i][j] == '#') cout << j << ' ';
cout << endl;
}
return;
}
for (int i = 1; i <= n; i ++ ){
if (!col[i] && !dg[r + i] && !ndg[n + r - i]){
col[i] = dg[r + i] = ndg[n + r - i] = true;
g[r][i] = '#';
dfs(r + 1);
col[i] = dg[r + i] = ndg[n + r - i] = false;
g[r][i] = '.';
}
}
}
int main(){
cin >> n;
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= n; j ++ )
g[i][j] = '.';
dfs(1);
printf("%d\n", num);
return 0;
}
直接记录答案
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 15, M = 30;
int path[N];
bool col[N], dg[M], ndg[M];
int n;
int num;
void dfs(int r){
if (r == n + 1){
num ++ ;
if (num <= 3){
for (int i = 1; i <= n; i ++ )
cout << path[i] << ' ';
cout << endl;
}
return;
}
// 当行数r确定,遍历列数i
for (int i = 1; i <= n; i ++ ){
if (!col[i] && !dg[r + i] && !ndg[n + r - i]){
col[i] = dg[r + i] = ndg[n + r - i] = true;
path[r] = i;
dfs(r + 1);
col[i] = dg[r + i] = ndg[n + r - i] = false;
path[r] = 0;
}
}
}
int main(){
cin >> n;
dfs(1);
printf("%d\n", num);
return 0;
}