UVA 439 Knight Moves

来源:互联网 发布:怎样用淘宝客推广 编辑:程序博客网 时间:2024/06/05 22:35

题目

骑士移动

分析

bfs.

思路

将起点标记为已走过并入队;
while (队列非空) {
    出队一个点p;
    if (p这个点是终点)
        break;
    否则沿给定方向探索点,if (该点有路可走,并且还没走过)
        将相邻的点标记为已走过并入队,它的前趋就是刚出队的p点;
}
    if (p点是终点) {
        打印路径长;
        while (p点有前趋) {
            p点=p点的前趋;
            打印路径长;
        }
    } else
    没有路线可以到达终点;
}

代码

#include <cstdio>#include <cstring>#define N 9int map[N][N];struct point {    int x, y, s;} que[N*N];int head, tail;int next[8][2] = {{2, 1}, {1, 2}, {2,-1}, {1, -2}, {-2, -1}, {-1, -2}, {-2, 1}, {-1, 2}};int bfs(int startx, int starty, int p, int q){    int l = 0;    memset(map, 0, sizeof(map));    map[startx][starty] = 1;    head = tail = 1;    que[tail].x = startx; que[tail].y = starty; que[tail].s = 0;    tail++;    while (head < tail) {        if (startx == p && starty == q) break;        int flag = 0;        for (int i = 0; i < 8; i++) {            int tx = que[head].x + next[i][0];            int ty = que[head].y + next[i][1];            if (tx<1 || tx>8 || ty<1 || ty>8) continue;            if (map[tx][ty] == 0) {                map[tx][ty] = 1;                que[tail].x = tx; que[tail].y = ty; que[tail].s = que[head].s + 1;                tail++;            }            if (tx == p && ty == q) {                flag = 1;                break;            }        }        if (flag == 1) break;        head++;    }    if (head == tail) l = 0;    else l = que[tail-1].s;    return l;}int main(void){    int startx, starty, p, q;    char a[3], b[3];    while (~scanf("%s%s", a, b)) {/* a -> 1 */        startx = a[0] - 'a' +1; starty = a[1] - '0';        p = b[0] - 'a' + 1; q = b[1] - '0';        printf("To get from %s to %s takes %d knight moves.\n", a, b, bfs(startx, starty, p, q));    }    return 0;}
0 0
原创粉丝点击