poj1321 棋盘问题
中文题不解释了
方法:深度优先搜索
遍历棋盘,将第一个棋子从开始位置到棋盘结束位置依次放下,第一个棋子确定下之后,同行同列的位置设为不能放置棋子,如果有第二个棋子,则将第二个棋子依次放在第一个棋子放下位置之后的其它位置,同行同列的位置设为不能放置棋子,一直到第N个棋子。假设到达最后一个位置放完棋子后还剩下有棋子,表明这种方法不成功返回。
#include <stdio.h>
#include <string.h>
#define MAX 9
int fun(char board[MAX][MAX], int row, int col, int n, int k)
{
if(board[row][col] == '.')
return 0;
if(k == 1)
return 1;
int i, j, count = 0;
char temp_board[MAX][MAX];
memcpy(temp_board, board, sizeof(char) * MAX * MAX);
for(i = 0; i < n; i++)
temp_board[i][col] = '.';
for(j = 0; j < n; j++)
temp_board[row][j] = '.';
for(i = (col + 1 >= n ? row + 1 : row); i < n; i++)
{//这里的保证temp_board[i][j]为下一个位置
for(j = (i == row ? col + 1 : 0); j < n; j++)
{
count += fun(temp_board, i, j, n, k - 1);
}
}
return count;
}
int main()
{
freopen("input.txt", "r", stdin);
freopen("out.txt", "w", stdout);
int n, k;
char board[MAX][MAX], temp_board[MAX][MAX];
while(1)
{
scanf("%d%d", &n, &k);
if(n == -1 && k == -1)
break;
int i, j, count = 0;
for(i = 0; i < n; i++)
scanf("%s", board[i]);
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{//依次放在棋盘上
memcpy(temp_board, board, sizeof(char) * MAX * MAX);
count += fun(temp_board, i, j, n, k);
}
}
printf("%d\n", count);
}
return 0;
}