现在的位置: 首页 > 综合 > 正文

POJ 1321 棋盘问题

2018年01月17日 ⁄ 综合 ⁄ 共 1199字 ⁄ 字号 评论关闭
棋盘问题
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 23798   Accepted: 11778

Description

在一个给定形状的棋盘(形状可能是不规则的)上面摆放棋子,棋子没有区别。要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列,请编程求解对于给定形状和大小的棋盘,摆放k个棋子的所有可行的摆放方案C。

Input

输入含有多组测试数据。 
每组数据的第一行是两个正整数,n k,用一个空格隔开,表示了将在一个n*n的矩阵内描述棋盘,以及摆放棋子的数目。 n <= 8 , k <= n 
当为-1 -1时表示输入结束。 
随后的n行描述了棋盘的形状:每行有n个字符,其中 # 表示棋盘区域, . 表示空白区域(数据保证不出现多余的空白行或者空白列)。 

Output

对于每一组数据,给出一行输出,输出摆放的方案数目C (数据保证C<2^31)。

Sample Input

2 1
#.
.#
4 4
...#
..#.
.#..
#...
-1 -1

Sample Output

2
1

Source

解题思路:

这道问题的解决应该很容易了,裸裸的DFS,只要做好回溯和标记就行了。

分别用两个数组来标记行和列,然后就这样下去一直递归下去就行了。

代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;

#define maxn 10

bool row[maxn], col[maxn];
bool map[maxn][maxn];
int ans, n, m;

void input()
{
    char ch;
    memset(map, 0, sizeof(map));
    getchar();
    
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            ch = getchar();
            if (ch == '#')
                map[i][j] = true;
            else
                map[i][j] = false;
        }
        getchar();
    }
}

void dfs(int pos, int a)
{
    if (a == m)
    {
        ans++;
        return;
    }
    
    while ( pos < n * n )
    {
        int x = pos / n;
        int y = pos % n;
        if (map[x][y] && !row[x] && !col[y])
        {
            row[x] = col[y] = true;
            dfs(pos + 1, a + 1);//a是棋子的个数
            row[x] = col[y] = false;
        }
        pos++;
    }
}

int main(void)
{

    while (~scanf("%d%d", &n, &m))
    {
        if ( n==-1&&m==-1 )
            break;
        input();
        memset(row, 0, sizeof(row));
        memset(col, 0, sizeof(col));
        ans = 0;
        dfs(0, 0);
        printf("%d\n", ans);
    }
    return 0;
}

抱歉!评论已关闭.