poj2488

Problem : A Knight’s Journey

Description:给你一个棋盘,问骑士能否不重复的游历整个棋盘。骑士可以运动的方向如题目图所示。

Solution:深度优先搜索。题目要求按字典序输出,所以一定要注意搜索的顺序。

Code(C++):

#include <iostream>
#include <cstring>

using namespace std;

struct point
{
    int x;
    int y;
} index[8];

int c[100][100];
int n,len,wid;
char ans[1000];
int k;
int count;

bool dfs(point p)
{
    point next;
    if(count==len*wid)
        return true;
    for(int i=0; i<8; i++)
    {
        next.x=p.x+index[i].x;
        next.y=p.y+index[i].y;
        if(next.x>=0&&next.y>=0&&next.x<wid
                &&next.y<len&&c[next.x][next.y]==0)
        {
            c[next.x][next.y]=1;
            count++;
            ans[k++]='A'+next.x;
            ans[k++]='1'+next.y;
            if(dfs(next))
                return true;
            c[next.x][next.y]=0;
            count--;
            k-=2;
        }
    }
    return false;
}

int main()
{
    index[0].x=-2;index[0].y=-1;
    index[1].x=-2;index[1].y=1;
    index[2].x=-1;index[2].y=-2;
    index[3].x=-1;index[3].y=2;
    index[4].x=1;index[4].y=-2;
    index[5].x=1;index[5].y=2;
    index[6].x=2;index[6].y=-1;
    index[7].x=2;index[7].y=1;


    cin>>n;
    int q=1;
    while(n--)
    {
        memset(c,0,sizeof(c));
        count=1;
        k=2;
        memset(ans,'0',sizeof(ans));
        cin>>len>>wid;
        point here;
        here.x=0;
        here.y=0;
        cout<<"Scenario #"<<q++<<":"<<endl;
        c[here.x][here.y]=1;
        ans[0]='A';
        ans[1]='1';
        if(dfs(here))
        {
            for(int i=0; i<k; i++)
                cout<<ans[i];
            cout<<endl;
        }
        else
            cout<<"impossible"<<endl;
        cout<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值