zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    


  • 相关阅读:
    js中this的用法
    js原型链与继承(初体验)
    关于C语言指针中的p++与p+i
    react todolist
    react表单提交
    react条件渲染
    react初体验
    初次接触express
    阿里内推在线编程题(返回元素的选择器)
    模块初始化
  • 原文地址:https://www.cnblogs.com/dollarzhaole/p/3188961.html
Copyright © 2011-2022 走看看