先贴我的
#define DeBUG
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <string>
#include <set>
#include <sstream>
#include <map>
#include <bitset>
using namespace std ;
#define zero {0}
#define INF 2000000000
#define EPS 1e-6
typedef long long LL;
const double PI = acos(-1.0);
inline int sgn(double x)
{
return fabs(x) < EPS ? 0 : (x < 0 ? -1 : 1);
}
int n;
char mp[10][10];
int maxx;
int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
bool ok(int x, int y)//四个方向没问题测试
{
int nx, ny;
if (mp[x][y] == 'X' || mp[x][y] == '@' || y >= n || x >= n)
return false;
for (int i = 0; i < 4; i++)
{
nx = x + dir[i][0];
ny = y + dir[i][1];
while (nx >= 0 && ny >= 0 && nx < n && ny < n && mp[nx][ny] != 'X')
{
if (mp[nx][ny] == '@')
return false;
nx += dir[i][0];
ny += dir[i][1];
}
}
return true;
}
int dfs(int x, int y, int cnt)
{
maxx = max(maxx, cnt);
if(y>n)
return 0;
for (int j = x; j < n; j++)//竖着来放
{
if (ok(j, y))
{
mp[j][y] = '@';
dfs(j + 2, y, cnt + 1);
mp[j][y] = '.';
}
}
for (int i = 0; i < n; i++)//横着来放
{
if (ok(i, y))
{
mp[i][y] = '@';
dfs(i, y + 1, cnt + 1);
mp[i][y] = '.';
}
}
dfs(0,y+1,cnt);//漏掉这里,八皇后定势思维
return 0;
}
int main()
{
#ifdef DeBUGs
freopen("C:\\Users\\Sky\\Desktop\\1.in", "r", stdin);
#endif
while (scanf("%d", &n), n)
{
maxx = 0;
for (int i = 0; i < n; i++)
{
scanf("%s", mp[i]);
}
dfs(0, 0, 0);
printf("%d\n", maxx);
}
return 0;
}
再贴高手的
#define DeBUG
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <string>
#include <set>
#include <sstream>
#include <bitset>
using namespace std ;
#define zero {0}
#define INF 2000000000
#define EPS 1e-6
typedef long long LL;
const double PI = acos(-1.0);
inline int sgn(double x)
{
return fabs(x) < EPS ? 0 : (x < 0 ? -1 : 1);
}
char map[5][5];
int maxnum;
int n;
bool canBuild(int row, int col)
{
int i, j;
for (i = row; i >= 0; i--)
{
if (map[i][col] == 'O')return false;
if (map[i][col] == 'X')break;
}
for (j = col; j >= 0; j--)
{
if (map[row][j] == 'O')return false;
if (map[row][j] == 'X')break;
}
return true;
}
void dfs(int i, int num)
{
int row, col;
if (i == n * n)
{
if (num > maxnum)
maxnum = num;
return ;
}
else
{
row = i / n;
col = i % n;//一个数据获取两个信息,行列
if (map[row][col] == '.' && canBuild(row, col))
{
map[row][col] = 'O';
dfs(i + 1, num + 1);
map[row][col] = '.';
}
dfs(i + 1, num);
}
}
int main()
{
#ifdef DeBUGs
freopen("C:\\Users\\Sky\\Desktop\\1.in", "r", stdin);
#endif
int i;
while (scanf("%d", &n), n)
{
maxnum = 0;
for (i = 0; i < n; i++)
{
scanf("%s", &map[i]);
}
dfs(0, 0);
printf("%d\n", maxnum);
}
return 0;
}