UVA439Knight Moves

来源:互联网 发布:成都软件开发怎么样 编辑:程序博客网 时间:2024/06/07 03:07

UVA-439

题意:给出两个坐标,求骑士从从第一个条到第一个坐标跳(中国象棋中马的走法)到第二个坐标要走多少步。
解题思路:一般遇到求最少步骤的就会先想到bfs。简单的广搜题目。

/*************************************************************************    > File Name: UVA-439.cpp    > Author: Narsh    >     > Created Time: 2016年07月20日 星期三 15时17分30秒 ************************************************************************/#include <iostream>#include <algorithm>#include <cstdio>#include <cstring>using namespace std;struct node{    int x,y,l;}q[600000];const int MoVe[8][2]={1,2,1,-2,-1,2,-1,-2,2,1,2,-1,-2,1,-2,-1};int n,m,h,t,x,y;bool map[30][30];string s;int main() {//cout<<"s  b"<<endl;    while (cin>>s) {        h=t=0;        memset(map,true,sizeof(map));        q[++t].x=s[0]-'a'+1;        q[t].y=s[1]-'0';        q[t].l=0;        map[q[t].x][q[t].y]=false;        printf("To get from %c%c to ",s[0],s[1]);        cin>>s;        printf("%c%c takes ",s[0],s[1]);        n=s[0]-'a'+1;        m=s[1]-'0';        while (h < t) {            h++;            if (q[h].x == n && q[h].y == m) {                printf("%d knight moves.\n",q[h].l);                break;            }            for (int i = 0; i < 8; i++) {                x=q[h].x+MoVe[i][0];                y=q[h].y+MoVe[i][1];                if (1 <= x && x <= 8 && 1 <= y && y <= 8 && map[x][y]) {                    map[x][y]=false;                    t++;                    q[t].x=x;                    q[t].y=y;                    q[t].l=q[h].l+1;                }            }        }    }}
0 0