POJ1321棋盘问题

http://poj.org/problem?id=1321

题意 : 我能说这是迄今为止见到的POJ上第二道中文题吗,既然是中文也很好理解,就不详述了

思路 : 典型的深搜DFS ;

 

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std ;
const int maxn = 100 ;
int vis[maxn] ;
int ch[maxn][maxn] ;
int cnt = 0 ,n,k ;
int judge(int a,int b)//判断这个棋子的这一行和这一列是否还有别的可以放棋子的地方
{
    for(int i = 1 ; i <= n ; i++)
    {
        if(ch[a][i] == -1)
        return 0 ;
        if(ch[i][b] == -1)
        return 0 ;
    }
    return 1 ;
}
void dfs(int step,int col)//step代表的是步数,col代表着是放了棋子的个数
{
    if(col == k)
    {
        cnt++ ;
        return ;
    }
    if(step == n*n)
    return ;
    int a = step/n+1 ;//现在棋子所在位置的行和列
    int b = step%n+1 ;
    if(ch[a][b]&&judge(a,b))//这个点是#号并且这个点所在的行和列没有别的#了
    {
        ch[a][b] = -1 ;//代表着#这个点已经放上了
        dfs(step+1,col+1) ;
        ch[a][b] = 1 ;//表示那一种已经操作完毕,恢复原样,找下一种方法
    }
    dfs(step+1,col) ;//因为放法有很多种,所以可以本来的这里不放放下一个
    return ;
}
int main()
{
    while(~scanf("%d %d",&n,&k))
    {
        if(n == -1&&k == -1)
        break ;
        cnt = 0 ;
        char sh ;
        memset(ch,0,sizeof(ch)) ;
        for(int i = 1 ; i <= n ; i++)
        {
            for(int j = 1 ; j <= n ; j ++)
            {
                cin>>sh ;
                if(sh == '#')
                ch[i][j] = 1 ;//#标记为1代表是可以放棋子的
            }
        }
        dfs(0,0) ;
        cout<<cnt<<endl ;
    }
}
View Code

 

 

这是小优姐写的,简洁明了、

 

//Memory Time 
//184K   32MS 

#include<iostream>
using namespace std;

bool chess[9][9];
bool vist_col[9];  //列标记
int status;  //状态计数器
int n,k;

void DFS(int row,int num)  //逐行搜索,row为当前搜索行,num为已填充的棋子数
{
    if(num==k)
    {
        status++;
        return;
    }

    if(row>n)    //配合下面DFS(row+1,num); 语句使用,避免搜索越界
        return;

    for(int j=1;j<=n;j++)
        if(chess[row][j] && !vist_col[j])
        {
            vist_col[j]=true;  //放置棋子的列标记
            DFS(row+1,num+1);
            vist_col[j]=false; //回溯后,说明摆好棋子的状态已记录,当前的列标记还原
        }

    DFS(row+1,num);   //这里是难点,当k<n时,row在等于n之前就可能已经把全部棋子放好
                      //又由于当全部棋子都放好后的某个棋盘状态已经在前面循环时记录了
                      //因此为了处理多余行,令当前位置先不放棋子,搜索在下一行放棋子的情况
    return;
}

int main(int i,int j)
{
    while(cin>>n>>k)
    {
        if(n==-1 && k==-1)
            break;

        /*Initial*/

        memset(chess,false,sizeof(chess));
        memset(vist_col,false,sizeof(vist_col));
        status=0;

        for(i=1;i<=n;i++)
            for(j=1;j<=n;j++)
            {
                char temp;
                cin>>temp;
                if(temp=='#')
                    chess[i][j]=true;
            }

        DFS(1,0);  //注意初始化的值别弄错了
        cout<<status<<endl;
    }
    return 0;
}
View Code

 

 

 

转载于:https://www.cnblogs.com/luyingfeng/p/3282001.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值