UVa 439 - Knight Moves

来源:互联网 发布:软件开发费用组成 编辑:程序博客网 时间:2024/06/01 01:33
/*  思路:    1、BFS遍历,不必遍历全部    注意点:    1、8*8的棋盘格,骑士的走法与象棋中的马走法相同*/#include <cstdio>#include <cstring>const int MAX = 8;int visit[MAX][MAX];int dist[MAX][MAX];const int dir_x[] = {-1, -2, -2, -1, 1, 2, 2, 1};const int dir_y[] = {-2, -1, 1, 2, 2, 1, -1, -2};const int DIR = sizeof(dir_x) / sizeof(dir_x[0]);int st_y,st_x,ed_y,ed_x;int qu_x[MAX*MAX];int qu_y[MAX*MAX];void bfs(){    int front=0, rear=0;    dist[st_x][st_y] = 0;    if(st_x == ed_x && st_y == ed_y) return; //found    visit[st_x][st_y] = 1;    qu_x[rear]=st_x; qu_y[rear++]=st_y;    while(front < rear) {        st_x = qu_x[front]; st_y = qu_y[front++];        if(st_x == ed_x && st_y == ed_y) return; //found        for(int i=0; i<DIR; i++) {            int t_x = st_x + dir_x[i];            int t_y = st_y + dir_y[i];            if(!visit[t_x][t_y] && t_x>=0 && t_x<MAX && t_y>=0 && t_y<MAX) {                dist[t_x][t_y] = dist[st_x][st_y] + 1;                if(t_x == ed_x && t_y == ed_y) return; //found                visit[t_x][t_y] = 1;                qu_x[rear]=t_x; qu_y[rear++]=t_y;            }        }    }}int main (){    #ifndef ONLINE_JUDGE    freopen("in.txt", "r", stdin);    #endif    char st[4];    char ed[4];    while(scanf("%s%s", st, ed)==2) {        st_y = st[0] - 'a';        st_x = st[1] - '1';        ed_y = ed[0] - 'a';        ed_x = ed[1] - '1';        memset(visit, 0, sizeof(visit));        bfs();        printf("To get from %s to %s takes %d knight moves.\n", st, ed, dist[ed_x][ed_y]);    }    return 0;}


原创粉丝点击