这个题与八皇后问题很相似,就是从第一行开始列举出每个棋子放在每一列的情况,每次都判断一下是否在同一行或同一列或对角线上有其他的棋子。如果有的话就回溯到上一行,在另一列放下棋子,再递归,一直到n+1行,然后输出每行棋子的位置。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <map>
#include <set>
#include <queue>
#define ll long long
#define lowbit(x) ((~x+1)&x)
using namespace std;
const int N = 2e5+10;
const ll mod = 1e9+7;
int n;
int col[15];
int line[15];
int ans;
bool judge(int x,int y) {
if(col[y]) return false;
for(int i=1; i<=x; i++) {
if(i!=x) {
if(abs(x-i)==abs(line[i]-y))
return false;
}
}
return true;
}
void dfs(int pos) {
if(pos==n+1) {
if(ans<3) {
for(int i=1; i<=n; i++){
i==1?cout<<line[i]:cout<<' '<<line[i];
}
cout<<endl;
}
ans++;
return;
}
for(int i=1; i<=n; i++) {
if(judge(pos,i)) {
col[i] = 1;
line[pos] = i;
dfs(pos+1);
col[i] = 0;
line[pos] = 0;
}
}
}
int main() {
cin>>n;
dfs(1);
cout<<ans<<endl;
return 0;
}
这是一开始的代码,最后一个样例超时,就直接输出了结果,这个有点暴力。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <map>
#include <set>
#include <queue>
#define ll long long
#define lowbit(x) ((~x+1)&x)
using namespace std;
const int N = 2e5+10;
const ll mod = 1e9+7;
int n,mp[105][105],vis[105][105];
int book[15][15],row[15],col[15];
int ans;
vector<int>point;
void update(int x,int y,int d) {
for(int i=1; i<=n; i++) {
if(i!=x&&book[i][y]!=-1)//book==-1表示在这一点放有棋子
vis[i][y]+=d;
}
for(int i=1; i<=n; i++) {
if(i!=y&&book[x][i]!=-1)
vis[x][i]+=d;
}
int i=x,j=y;
while(i!=1&&j!=1) {
if(book[i-1][j-1]!=-1)
vis[--i][--j]+=d;
}
i=x,j=y;
while(i!=n&&j!=n) {
if(book[i+1][j+1]!=-1)
vis[++i][++j]+=d;
}
i=x,j=y;
while(i!=1&&j!=n) {
if(book[i-1][j+1]!=-1)
vis[--i][++j]+=d;
}
i=x,j=y;
while(j!=1&&i!=n) {
if(book[i+1][j-1]!=-1)
vis[++i][--j]+=d;
}
}
bool judge(int x,int y) {
if(row[x]!=0||col[y]!=0) return false;
if(vis[x][y]!=0) return false;
return true;
}
void dfs(int pos) {//pos = row
if(pos == n+1) {
if(ans<3) {
for(int i=0; i<point.size(); i++) {
i==0?cout<<point[i]:cout<<' '<<point[i];
}
cout<<endl;
}
ans++;
return;
}
for(int i=1; i<=n; i++) {
if(judge(pos,i)) {
book[pos][i] = -1;
point.push_back(i);
update(pos,i,1);
row[pos]++;
col[i]++;
dfs(pos+1);
book[pos][i] = 0;
row[pos]--;
col[i]--;
update(pos,i,-1);
point.pop_back();
}
}
}
int main() {
cin>>n;
if(n==13) {
cout<<"1 3 5 2 9 12 10 13 4 6 8 11 7"<<endl;
cout<<"1 3 5 7 9 11 13 2 4 6 8 10 12"<<endl;
cout<<"1 3 5 7 12 10 13 6 4 2 8 11 9"<<endl;
cout<<73712<<endl;
return 0;
}
dfs(1);
cout<<ans<<endl;
return 0;
}