HDUOJ Knight Moves解题报告

1.典型的bfs。

2.难点在剪枝部分。有一个记录所走step的数组,记录到每个点所走的步数,如果一个点没走过,放进队列中,如果一个点走过,比较原来这个点的step值和由当前点计算的值,如果大,另其等于当前点的step值+1;

3.这道题犯了超级低级的错误。。。写好了bfs()函数,结果在main()函数中没有添加bfs();语句,导致调试了好久得不到想要的结果。。。



#include <stdio.h>
#include <iostream>
#include <queue>
#include <cstring>

using namespace std;

struct Node
{
    int x, y;
} sta, end;

char a, c;
int b, d, i;
int step[9][9];
int che[8][2] = {{-1, +2}, {-2, +1}, {+1, +2}, {+2, +1}, {+2, -1}, {+1, -2}, {-1, -2}, {-2, -1}};

bool check(int aa, int bb)
{
    if( aa > 0 && aa <= 8 && bb > 0 && bb <= 8)
        return true;
    else return false;
}

void bfs()
{
    queue <int> q;
    q.push(sta.x);
    q.push(sta.y);
    while(!q.empty())
    {
        int xx = q.front();
        q.pop();
        int yy = q.front();
        q.pop();
        if (xx == end.x && yy == end.y)
            continue;
        for(i = 0; i <8; i++)
        {
            if(!check(xx + che[i][0], yy + che[i][1]))
                continue;
            if(!step[xx + che[i][0]][yy + che[i][1]] || step[xx + che[i][0]][yy + che[i][1]] > step[xx][yy] + 1)
            {
                step[xx + che[i][0]][yy + che[i][1]] = step[xx][yy] + 1;
                q.push(xx + che[i][0]);
                q.push(yy + che[i][1]);
            }
        }
    }
}


int main()
{
    while(scanf("%c", &a) != EOF)
    {
        memset(step, 0, sizeof(step));
        scanf("%d", &b);
        getchar();
        sta.x = a - 'a' + 1;
        sta.y = b;
        scanf("%c%d", &c, &d);
        getchar();
        end.x = c - 'a' + 1;
        end.y = d;

        bfs();
        cout << "To get from " << a << b <<" to " << c << d <<" takes " <<step[end.x][end.y]<<" knight moves."<< endl;


//        cout << sta.x << ' ' << sta.y << ' ' << end.x << ' ' << end.y <<endl;

    }
    return 0;
}


原文地址:https://www.cnblogs.com/dollarzhaole/p/3188964.html