一.原题链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=2
二.思路:八皇后问题,不过要一格一格搜,每个格子有选或者不选2种情况,注意到每一格最后要进入下一行,还有我的代码的最后一个要再判断一次能不能放。
三.代码:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
using namespace std;
const int INF = 1<<29;
int N, ans;
char mp[9][9];
bool isSet[9][9];
bool check(int i, int j)
{
if('X' == mp[i][j])
return false;
int k;
for(k = j - 1; k >= 0; k--){
if('X' == mp[i][k]){
break;
}
if(isSet[i][k])
return false;
}
for(k = i - 1; k >= 0; k--){
if('X' == mp[k][j]){
break;
}
if(isSet[k][j])
return false;
}
return true;
}
void dfs(int i, int j, int cnt)
{
if(N - 1 == j && N - 1 == i){
if(check(i, j))
cnt++;
ans = max(ans, cnt);
return;
}
if(N - 1 == j && i < N - 1){
if(check(i, j)){
isSet[i][j] = true;
dfs(i + 1, 0, cnt + 1);
isSet[i][j] = false;
}
dfs(i + 1, 0 , cnt);
return;
}
if(check(i, j)){
isSet[i][j] = true;
dfs(i, j + 1, cnt + 1);
isSet[i][j] = false;
}
dfs(i, j + 1, cnt);
}
int main()
{
//freopen("in.txt", "r", stdin);
int i, j;
while(cin>>N && N){
for(i = 0; i < N; i++)
for(j = 0; j < N; j++)
cin>>mp[i][j];
memset(isSet, 0, sizeof(isSet));
ans = -1;
dfs(0, 0, 0);
cout<<ans<<endl;
}
return 0;
}