棋盘问题

原题链接

题解

在棋盘中的每一个可以放得位置,有两种情况放或者不放,直接枚举这两种情况即可(做搜索的时候要注意搜索顺序)

代码如下

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <queue>
#include <sstream>
#include <set>
#include <cctype>
#define mem(a,b) memset(a,b,sizeof(a))

using namespace std;

typedef pair<int, int> PII;
const int N = 10;
char g[N][N];
int n, m;
bool row[N], col[N];//row是用来标记行,col用来标记列

int dfs(int x, int y, int s){
    if(s == m) return 1;
    if(y == n) y = 0, x ++;//列越界
    if(x == n) return 0;//行越界,直接返回
    

    int res = dfs(x, y + 1, s);//不放棋子的情况
    if(!row[x] && !col[y] && g[x][y] != '.'){
        row[x] = col[y] = true;
        res += dfs(x, y + 1, s + 1);//放棋子的情况
        row[x] = col[y] = false;
    }

    return res;
}

int main(){
    
    while(cin >> n >> m){
        if(n == -1 && m == -1) break;
        for(int i = 0; i < n; ++i)
            for(int j = 0; j < n; ++j)
                cin >> g[i][j];

        cout << dfs(0 , 0, 0) << endl;
    }

    return 0;
}
原文地址:https://www.cnblogs.com/Lngstart/p/13172065.html