该题是n皇后的变形,题意是:
给出n*n的棋盘,‘.’代表是空的,‘X’代表障碍物
让你判断最多可以放几个棋子使得任意一行,任意一列不会有两个棋子存在且中间没有墙的情况
这道题让我很纠结啊
本来还想按着n皇后的方法写,但是那种对应的是一行对应一个棋子
后来参考别人代码才知道怎么写
题中0代表可以放棋子,1代表放棋子,-1代表该处为障碍物
#include <cstdio>
#include <iostream>
#include <algorithm>
#define MAXN 100
#define ll long long
using namespace std;
int a[MAXN][MAXN];
int besttot, n;
void judge() {
int ok = 1;
int tot = 0;
for(int i=0; i<n; ++i) {
for(int j=0; j<n; ++j) {
if(a[i][j] == 1) {
tot++;
for(int k=i-1; k>=0&&a[k][j]!=-1; --k) {//up search
if(a[k][j] == 1) {
ok = 0;
break;
}
}
if(!ok) break;
for(int k=j-1; k>=0&&a[i][k]!=-1; --k) {//left search
if(a[i][k] == 1) {
ok = 0;
break;
}
}
if(!ok) break;
for(int k=j+1; k<n&&a[i][k]!=-1; ++k) {//right search
if(a[i][k] == 1) {
ok = 0;
break;
}
}
if(!ok) break;
for(int k=i+1; k<n&&a[k][j]!=-1; ++k) {//down search
if(a[k][j] == 1) {
ok = 0;
break;
}
}
}
}
if(!ok) break;
}
if(ok && tot>besttot)
besttot = tot;
}
void search(int row, int col) {
if(col == n) {
col = 0;
row++;
}
if(row == n) {
judge();
}
else {
if(a[row][col] == 0) {//每处棋盘对应3种情况
search(row, col+1);//该处不放棋子
a[row][col] = 1;
search(row, col+1);//该处放棋子
a[row][col] = 0;
}
else search(row, col+1);//该处不能放棋子
}
}
int main(void) {
char ch;
while(cin >> n, n) {
for(int i=0; i<n; ++i) {
getchar();
for(int j=0; j<n; ++j) {
scanf("%c", &ch);
ch == '.' ? a[i][j] = 0 : a[i][j] = -1;
}
}
besttot = 0;
search(0, 0);
cout << besttot << endl;
}
}
不记得之前写过这个题了,刚刚又把这个题A了一遍...
这次代码纯自己写的,感觉回溯比上一个代码直观
代码如下:
#include <cstdio>
#include <iostream>
#include <algorithm>
#define MAXN 10
#define ll long long
using namespace std;
int n;
int map[MAXN][MAXN];
int ans = 0;
int best = -1;
bool judge(int row, int col) {
if(map[row][col] == 1) {
return false;
}
int i = row;
int j = col;
while(1) {
--i;
if(i < 0)
break;
if(map[i][col] == -1)
return false;
if(map[i][col] == 1)
break;
}
while(1) {
--j;
if(j < 0)
break;
if(map[row][j] == -1)
return false;
if(map[row][j] == 1)
break;
}
return true;
}
void search(int row, int col) {
if(col >= n) {
row++;
col = 0;
}
if(row >= n) {
if(ans > best) {
best = ans;
}
// cout << "ans = " << ans << endl;
return ;
}
search(row, col+1);
if(judge(row, col)) {
map[row][col] = -1;
ans++;
search(row, col+1);
map[row][col] = 0;
ans--;
}
return ;
}
int main(void) {
while(scanf("%d", &n)!=EOF && n) {
char ch;
for(int i=0; i<n; ++i) {
getchar();
for(int j=0; j<n; ++j) {
ch = getchar();
if(ch == '.') {
map[i][j] = 0;
}
else map[i][j] = 1;
}
}
/*
for(int i=0; i<n; ++i) {
for(int j=0; j<n; ++j) {
printf("%d", map[i][j]);
}
cout << endl;
}
*/
best = -1;
ans = 0;
search(0, 0);
cout << best << endl;
}
return 0;
}