poj2488旧题重做标准DFS

注意:字典序。

其他没什么的了,主要是重新熟悉一下DFS的过程。。。久了就忘了。

#include<iostream>
#include<cstring>
using namespace std;
bool vis[25][25];
bool flag=0;
int p,q;
int dx[8] = {-2, -2, -1, -1, 1, 1, 2, 2};
int dy[8] = {-1, 1, -2, 2, -2, 2, -1, 1};   // 字典序。
char path[50];
void DFS(int depth,int x,int y)
{
    if(depth==p*q)                //DFS首先是结束条件
    {
        flag=true;
        return ;
    }
    for(int i=0;i<8&&flag==false;i++)    //然后直接对每一步情况进行分析,这里flag算一个剪枝
    {
        int new_x=x+dx[i];
        int new_y=y+dy[i];  //限制条件
        if(new_x > 0 && new_y > 0 && new_x <= q && new_y <= p && vis[new_y][new_x] == false)
        {//操作
            vis[new_y][new_x]=true;
            path[2*depth]=new_x+'A'-1;
            path[2*depth+1]=new_y+'1'-1;
            //递归
            DFS(depth+1,new_x,new_y);
            vis[new_y][new_x]=false;
        }
    }
}
void Init()
{
    for(int y = 1; y <= p; y ++)
            for(int x = 1; x <= q; x ++)
                vis[y][x] = false;
    flag=false;
    vis[1][1]=true;
    path[0]='A';
    path[1]='1';
}
int main()
{
    int T,t;
    cin>>T;
    t=1;
    while(t<=T)
    {
        cin>>p>>q;
        Init();
        DFS(1,1,1);
        if(flag)
        {
            cout<<"Scenario #"<<t<<':'<<endl;
            for(int i = 0; i < 2 * p*q; i ++)
            cout << path[i];
            cout << endl << endl;
        }
        else
        {
            cout<<"Scenario #"<<t<<':'<<endl;
            cout<<"impossible" << endl << endl;
        }
        t++;
    }
    return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值