poj 2488 -- A Knight's Journey (DFS)

大意就是给定大小棋盘,可以以任意位置为起点,让马跳遍棋盘的每个位置而不重复,普通的DFS


#include<iostream>
#include<cstring>
using namespace std;
int chess[30][30];            //标记棋盘当前位置是否走过
char ans[100000];             //存答案
int p,q;
int cnt;                      //记录已走过点的个数
bool dfs(int x,int y)
{
    if(cnt==p*q)
        return true;
    if(x<1||y<1||x>p||y>q||chess[x][y]==1)
        return false;
    ans[cnt*2]=x+'A'-1;
    ans[cnt*2+1]=y+'0';
    chess[x][y]=1;
    cnt++;
    if(dfs(x-2,y-1))            //题目要求的顺序,字典序
        return true;
    if(dfs(x-2,y+1))
        return true;
    if(dfs(x-1,y-2))
        return true;
    if(dfs(x-1,y+2))
        return true;
    if(dfs(x+1,y-2))
        return true;
    if(dfs(x+1,y+2))
        return true;
    if(dfs(x+2,y-1))
        return true;
    if(dfs(x+2,y+1))
        return true;
    cnt--;
    chess[x][y]=0;
    return false;
}
bool loop()                //循环每个起点,判断当前起点成不成立
{
    for(int i=1; i<=p; i++)
        for(int j=1; j<=q; j++)
            if(dfs(i,j))
                return true;
    return false;
}
int main()
{
    int n;
    int num=1;
    cin>>n;
    while(n--)
    {
        for(int i=0; i<30; i++)
            for(int j=0; j<30; j++)
                chess[i][j]=0;
        memset(ans,0,100000);
        cnt=0;
        cin>>q>>p;
        cout<<"Scenario #"<<num++<<":"<<endl;
        if(loop())
        {
            ans[cnt*2]=0;
            cout<<ans<<endl;
        }
        else
            cout<<"impossible"<<endl;
        cout<<endl;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值