poj dfs相关之1321 棋盘问题

来源:互联网 发布:淘宝平均停留时间 编辑:程序博客网 时间:2024/05/18 01:30

poj dfs相关之1321 棋盘问题

用循环的原因是不论行和列都应该在0~n的范围遍历
因为行是从0遍历到n-1的,所以只需要对列使用一个mark数组

#include<iostream>#include<cstring>#include<cstdio>#include<algorithm>using namespace std;int n, k, ans;char space[8][8];bool Colmark[8];void dfs(int row, int res){    if (res == k)    {        ans++;        return;    }    int i, j;    for (i = row; i < n; i++)    {        for (j = 0; j < n; j++)        {            if (!Colmark[j] && space[i][j]=='#')            {                Colmark[j] = 1;                dfs(i + 1,res + 1);                Colmark[j] = 0;            }        }    }}int main(){    freopen("1.txt", "r", stdin);    int i, j, sum;    while (scanf("%d%d", &n, &k) != EOF&&n != -1 && k != -1)    {        for (i = 0; i < n; i++)        {            scanf("%s", &space[i]);        }        ans = 0;        memset(Colmark, 0, sizeof(Colmark));        dfs(0, 0);        printf("%d\n", ans);    }}
原创粉丝点击