Knight Moves UVA

来源:互联网 发布:徐州工程学院报修软件 编辑:程序博客网 时间:2024/05/18 02:19

给出国际象棋棋盘中的两个点,求马从一个点跳到另一个点的最少步数。

#include<iostream>#include<cstdio>#include<queue>#include<cstring>using namespace std;int x, y;char cx, cy;const int maxn = 10;int d[maxn][maxn];int dc[] = { 1,2,2,1,-1,-2,-2,-1 };int dr[] = { -2,-1,1,2,2,1,-1,-2 };struct Node{    int x, y;    Node(int x = 0, int y = 0) :x(x), y(y) {}};Node p[maxn][maxn];bool in(int x, int y){    return x >= 1 && x <= 8 && y >= 1 && y <= 8;}void BFS(){    queue<Node> Q;    Node u(x, cx - 'a' + 1);    Q.push(u);    memset(d, -1, sizeof(d));  //注意初始化顺序,此句与下一句不可颠倒    d[x][cx - 'a' + 1] = 0;    while (!Q.empty())    {        Node u = Q.front();        Q.pop();        if (u.x == y && u.y == (cy - 'a' + 1))            return;        for (int i = 0; i < 8; ++i)        {            Node v(u.x + dr[i], u.y + dc[i]);            if (in(v.x, v.y) && d[v.x][v.y] < 0)            {                d[v.x][v.y] = d[u.x][u.y] + 1;                p[v.x][v.y] = u;                Q.push(v);            }        }    }}int main(){    while (cin>>cx>>x>>cy>>y)    {        BFS();        cout << "To get from " << cx << x << " to " << cy << y << " takes " << d[y][cy - 'a' + 1] << " knight moves." << endl;    }}
0 0
原创粉丝点击