菜鸡来发代码了。
写这题真是命途多舛。
忘记带纸笔了,所以对角线找规律就没找到,然后存了个n*n的数组来看有没有被占领,vis++和vis–。并且写的时候,vis[x][y]还写笔误了,debug了好久。写完递归才发现dfs里参数只需要行,不需要列。
结果最后一个点超时了。
看了题解才发现,可以用i+j表示左对角线,i-j+n表示右对角线(果然还是太菜了啊,都没有发现和相等这个问题)。
修改了一下代码,AC了。
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <algorithm>
using namespace std;
int n, cnt;
int ans[15], vis[15][15], row[15], col[15], rd[30], ld[30];
void influence(int x, int y){
row[x] = 1;
col[y] = 1;
ld[x+y] = 1;
rd[x-y+n] = 1;
}
void noInfluence(int x, int y){
row[x] = 0;
col[y] = 0;
ld[x+y] = 0;
rd[x-y+n] = 0;
}
void dfs(int x){
if(x == n+1){
cnt ++;
if(cnt <= 3){
printf("%d", ans[1]);
for(int i = 2; i <= n; i ++){
printf(" %d", ans[i]);
}
printf("\n");
}
return;
}
if(x > n+1) return;
for(int i = 1; i <= n; i ++){
if(row[x] == 0 && col[i] == 0 && ld[x+i] == 0 && rd[x-i+n] == 0){
influence(x, i);
ans[x] = i;
dfs(x+1);
noInfluence(x, i);
}
}
}
int main(){
scanf("%d", &n);
dfs(1);
printf("%d", cnt);
return 0;
}