UVa 439 - Knight Moves (BFS)

来源:互联网 发布:阿里云smtp服务器地址 编辑:程序博客网 时间:2024/06/05 04:31

简单的BFS。


#include <cstdio>#include <queue>#include <cstring>#include <cstdlib>using std :: queue;const int maxv = 10;int desk[maxv][maxv];int const dx[maxv] = {-1, -2, 1, 2};int const dy[maxv] = {-2, -1, 2, 1};struct Point{    int x, y;};void bfs(Point t) {    memset(desk, 0, sizeof(desk));    queue<Point> s;    s.push(t);    desk[t.x][t.y] = 1;    while(!s.empty()) {        Point T;        Point p = s.front(); s.pop();        for(int i = 0; i < 4; i++)            for(int j = 0; j < 4; j++)                if(dx[i] != dy[j]&& dx[i] != -dy[j])                    if(p.x + dx[i] >= 0&& p.x + dx[i] < 8                       && p.y + dy[j] >= 0&& p.y + dy[j] < 8                       && !desk[p.x + dx[i]][p.y + dy[j]]) {                        desk[p.x + dx[i]][p.y + dy[j]] = desk[p.x][p.y] + 1;                        T.x = p.x + dx[i];                        T.y = p.y + dy[j];                        s.push(T);                       }    }}int main () {    char str[maxv];    while(gets(str) != NULL) {        Point star;        star.x = str[0] - 'a';        star.y = str[1] - '1';        bfs(star);        printf("To get from %c%c to %c%c takes %d knight moves.\n",               str[0], str[1], str[3], str[4], desk[str[3] - 'a'][str[4] - '1'] - 1);    }    return 0;}


0 0
原创粉丝点击