简单回溯
CODE:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
using namespace std;
const int SIZE = 6;
int MAX;
int maze[SIZE][SIZE];
int N;
int check(int r, int c)
{
int i;
for(i = r-1; i >= 0; i--)
{
if(maze[i][c] == 'Y') return 0;
if(maze[i][c] == 'X') break;
}
for(i = c-1; i >= 0; i--)
{
if(maze[r][i] == 'Y') return 0;
if(maze[r][i] == 'X') break;
}
return 1;
}
void dfs(int i, int s)
{
if(i == N*N)
{
MAX = max(MAX, s);
return ;
}
int r = i/N, c = i%N; //行,列。
if(maze[r][c] == '.' && check(r, c))
{
maze[r][c] = 'Y';
dfs(i+1, s+1);
maze[r][c] = '.';
}
dfs(i+1, s);
}
int main()
{
int i, j;
while(~scanf("%d", &N), N)
{
getchar();
memset(maze, 0, sizeof(maze));
for(i = 0; i < N; i++)
{
for(j = 0; j < N; j++)
{
scanf("%c", &maze[i][j]);
}
getchar();
}
MAX = -1;
dfs(0, 0);
printf("%d\n", MAX);
}
return 0;
}
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
using namespace std;
const int SIZE = 6;
int MAX;
int maze[SIZE][SIZE];
int N;
int check(int r, int c)
{
int i;
for(i = r-1; i >= 0; i--)
{
if(maze[i][c] == 'Y') return 0;
if(maze[i][c] == 'X') break;
}
for(i = c-1; i >= 0; i--)
{
if(maze[r][i] == 'Y') return 0;
if(maze[r][i] == 'X') break;
}
return 1;
}
void dfs(int i, int s)
{
if(i == N*N)
{
MAX = max(MAX, s);
return ;
}
int r = i/N, c = i%N; //行,列。
if(maze[r][c] == '.' && check(r, c))
{
maze[r][c] = 'Y';
dfs(i+1, s+1);
maze[r][c] = '.';
}
dfs(i+1, s);
}
int main()
{
int i, j;
while(~scanf("%d", &N), N)
{
getchar();
memset(maze, 0, sizeof(maze));
for(i = 0; i < N; i++)
{
for(j = 0; j < N; j++)
{
scanf("%c", &maze[i][j]);
}
getchar();
}
MAX = -1;
dfs(0, 0);
printf("%d\n", MAX);
}
return 0;
}