搜索——1015

来源:互联网 发布:淘宝删除邀请我的回答 编辑:程序博客网 时间:2024/06/07 05:58

题意:国际象棋。给出起点和终点,问最少几步可以跳过去。

思路:找出从起点出发到达终点的所有路径路径,然后再从这些路径中寻找最短路径

scanf跳过空格读字符

#include <iostream>

#include <stdio.h>
#include <memory.h>
#include <queue>
using namespace std;


int xx[8] = {1, 2, 1, 2, -1, -2, -1, -2};
int yy[8] = {2, 1, -2, -1, 2, 1, -2, -1};


char c1, c2;
int b1, b2, x1, x2, y1, y2;
bool ch[10][10];


struct point
{
    int x, y, step;
}n, m;


int main()
{
    int i;
    while(cin>>c1>>b1>>c2>>b2)
    {
        x1 = c1 - 'a' + 1;
        x2 = c2 - 'a' + 1;
        y1 = b1;
        y2 = b2;
        memset(ch, false, sizeof(ch));
        n.x = x1; n.y = y1;
        n.step = 0;
        ch[n.x][n.y] = true;
        queue<point> P;
        P.push(n);
        while(!P.empty())
        {
            m = P.front();
            P.pop();
            if(m.x == x2 && m.y == y2) break;
            for(i = 0; i < 8; i++)
            {
                n.x = m.x + xx[i];
                n.y = m.y + yy[i];
                n.step = m.step + 1;
                if(n.x>0 && n.x<=8 && n.y>0 && n.y<=8 && !ch[n.x][n.y])
                {
                    ch[n.x][n.y] = true;
                    P.push(n);
                }
            }
        }
        printf("To get from %c%d to %c%d takes %d knight moves.\n",
                c1, y1, c2, y2, m.step);
    }


    return 0;
}
0 0
原创粉丝点击