[POJ] [1321] Chessboard Problem

Problem Description

Loading...

Problem Analysis

Not a particularly hard search problem
but once you panic it’s easy to get messy
and then you get distracted by someone else’s code and lose your own train of thought

The search just counts how many ways can reach $n==k$
so all you need is to set up the search conditions properly
See the code comments for details

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include<stdio.h>
char map[10][10];
bool flag[12];
int n,k;
int cnt;
void dfs(int m,int x) {
    if(m==k) {
        cnt++;
        return; //有一种方案达到了k个棋子 
    }
    if(x==n)
        return ; //到达边界而退出 
    for(int i=0; i<n; i++) { //在当前行尝试各个列能否放棋子 
        if(map[x][i]=='#'&&!flag[i]) {
            flag[i]=true;
            dfs(m+1,x+1);
            flag[i]=false;
        }
    }
    dfs(m,x+1); 
//  与八皇后问题不同的一点
//  因为当前行也许可以不放棋子
//  所以跳过这一行搜索下一行 
}
int main() {
    while(scanf("%d %d",&n,&k),n!=-1||n!=-1) {
        getchar();
        for(int i=0; i<n; i++) {
            flag[i]=false;
            for(int j=0; j<n; j++) {
                scanf("%c",&map[i][j]);
            }
            getchar();
        }
        cnt=0;
        dfs(0,0);//从第0行0个棋子开始搜索 
        printf("%d\n",cnt);
    }
    return 0;
}
This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...