poj 1321(简单的dfs,棋盘问题)

题意就是有一个n*n的棋盘,只有#能放棋子,而且每一横行纵行只能同时存在一个棋子。问摆起方案。

棋盘问题应该算是简单的dfs中的典型吧, 吐一句槽,刚写这一题的时候以为是只有"."才能放棋,debug了半天。。才发现题目看错了。
关于做法,首先把棋盘用一个字符数组存起来,然后由于每一横行纵行只能存在唯一棋子,所以我们只需要讨论纵行的情况。

用一个布尔数组来判断该步是否走过,即可,由于数据很小所以也不用考虑剪枝。

//#include<bits/stdc++.h>
#include<iostream>
#include<cstring>
using namespace std;
const int N = 2e5 + 7;
const int M = 1e3 + 7;
const int Q = 1000000007;
const int INF = 0x3f3f3f;
typedef long long ll;
typedef double dl;
int n,k,t,ans = 0;
bool a[9]; // 存储该横行是否走过
char chess[9][9]; // 存储棋盘
void dfs(int cnt,int row) // cnt表示已放棋子数,row表示当前横行
{
    if(cnt == k){ // 如果放棋子数达到预期棋子数,更新ans
        ans++;
        return ;
    }
    if(row >= n) return ; // 防止栈溢出
    for(int i = 0;i < n;++i){ // i表示列数
        if(chess[row][i] == '#' && !a[i]){
            a[i] = true; // 走该位置
            dfs(cnt + 1,row + 1); // 走该位置递归
            a[i] = false; // 不走该位置
        }
    }
    dfs(cnt,row + 1); // 不走当前横行
}
int main()
{
    while(cin >> n >> k && n != -1){
        for(int i = 0;i < n;++i)
            cin >> chess[i];
        memset(a,false,sizeof a);
        dfs(0,0);
        cout << ans << endl;
        ans = 0; // 记得刷新全局变量ans
    }
    return 0;
}

感觉跟n皇后问题差不多的。。。

猜你喜欢

转载自blog.csdn.net/qq_41791981/article/details/80508626