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;
    }
}

原文链接: https://www.cnblogs.com/dollarzhaole/archive/2012/03/14/3188961.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    A Knight's Journey

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/44180

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 下午8:50
下一篇 2023年2月8日 下午8:50

相关推荐