POJ1321 Checkerboard problem (DFS entry problem)

Description

Placing the chess pieces on a chessboard of a given shape (the shape may be irregular) makes no difference. It is required that any two chess pieces cannot be placed in the same row or column in the chessboard. Please program to solve all the feasible placement schemes C of k chess pieces for a chessboard of a given shape and size.
————————————————
Input
contains multiple sets of test data.
The first line of each group of data is two positive integers, nk, separated by a space, which means that the chessboard will be described in an n*n matrix and the number of chess pieces placed. n <= 8, k <= n
when it is -1 -1, it means the end of input.
The following n lines describe the shape of the chessboard: each line has n characters, where # represents the chessboard area, and. Represents the blank area (the data guarantees that there are no extra blank rows or blank columns).
————————————————
Output
For each set of data, one line of output is given, and the number of output solutions is C (data guarantee C<2^31).
————————————————
Sample Input

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

Sample Output

2
1

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int n, k, ans;
bool vis[100];
char str[10][10];
void dfs(int r, int k)
{
    
    
    if(k==0)//判断边界,此时棋子已经放完
    {
    
    
        ans++;
        return;
    }
    for(int i=r; i<n; i++)//每次都从放过棋子下一行开始搜索,保证不重复(每次传输行数加一)
    {
    
    
        for(int j=0; j<n; j++)
        {
    
    
            //循环保证行不重复,vis保证列不重复
            if(str[i][j]=='.' || vis[j]==1)
                continue;//不满足条件直接跳过
            vis[j] = 1;//标记
            dfs(i+1, k-1);//继续下一次标记
            vis[j] = 0;//恢复初始状态
        }
    }
}
int main(void)
{
    
    
    while(1)
    {
    
    
        scanf("%d %d", &n, &k);
        getchar();
        if(n==-1 && k==-1)
            break;
        memset(str, '\0', sizeof(str));
        memset(vis, false, sizeof(vis));
        ans = 0;
        for(int i=0; i<n; i++)
        {
    
    
            for(int j=0; j<n; j++)
                str[i][j]=getchar();
            getchar();
        }
        dfs(0, k);//从第0行开始放,此时手中还剩k个棋子
        printf("%d\n", ans);
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/WTMDNM_/article/details/108550420