A Knight's Journey

1.大牛们都说是简单的DFS,想自己A一道,结果还是没A出来,最后还是看了别人的结题报告;

2.递归还是不熟悉,做DFS用递归,总是出现错误。通过这个题,用递归函数,首先要包含一个结束条件,然后才能用递归;

3.自己第一遍写代码的过程中,学会了用sort()函数对结构体的某一个元素进行排序的方法,参考(C/C++ sort函数的用法_真爱无限_新浪博客);

4.自始至终对整道题所要用的变量没有合理的安排,之前做的稍微复杂点的题都这样,如何改进是个问题


以下是代码:


#include <iostream>
#include <cstring>
using namespace std;
int x, y ,tstep, n;
bool used[26][26];
int dir[8][2] = {-1,-2,1,-2,-2,-1,2,-1,-2,1,2,1,-1,2,1,2};
bool rel;
struct Node
{
    int dx;
    char dy;
} path[26];
void inital()
{
    tstep = 0;
    rel = false;
    memset(used, 0, sizeof(used));
}
void bfs(int a, int b)
{
    if(rel) return;
    path[tstep].dx = a + 1;
    path[tstep].dy = b + 'A';
    tstep ++ ;
    if(tstep == x * y)
    {
        rel = true;
        return;
    }
    used[a][b] = 1;
    for(int i = 0; i < 8; i++)
    {
        int xx = a + dir[i][0];
        int yy = b + dir[i][1];
        if(xx >= 0 && xx < x && yy >= 0 && yy < y && used[xx][yy] == 0)
        {
            bfs(xx, yy);
            tstep--;
        }
    }
    used[a][b] = 0;
}

int main()
{
    cin >> n;
    int m = n;
    while(n--)
    {
        cin >> x >> y;
        inital();
        bfs(0, 0);
        cout << "Scenario #"<< m - n << ":" << endl;
        if(rel)
        {
            for(int i = 0; i < x * y; i++)
                cout << path[i].dy << path[i].dx;
            cout << endl << endl;
        }
        else cout << "impossible" << endl << endl;
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值