uva_439 - Knight Moves

来源:互联网 发布:htc手机移动网络不可用 编辑:程序博客网 时间:2024/05/29 03:16
/*      题目大意:告诉你国际象棋中马的初始位置和目标位置,算出它的最小步数 *      解题思路:首先要得知道国际象棋的马如何行动,幸好我玩过,它比中国的马 * 多走一格,也就是走‘目’字,然后枚举出马的行动方向,用BFS计算出最小步数。*/#include <cstdio>#include <cstring>#include <queue>#include <algorithm>using namespace std;#define MAX_ROW         8#define MAX_COL         8#define DIR             8struct Point{    int x, y, time;};int dir[][2] = {    {-2, -1}, {-2, 1}, {-1, 2}, {1, 2},    {2, 1}, {2, -1}, {1, -2}, {-1, -2}};int target_x, target_y;bool visited[MAX_ROW+1][MAX_COL+1];int BFS(int x, int y){    queue<Point> Q;    visited[x][y] = true;    Point p;    if( p.x == target_x && p.y == target_y ) return 0;    p.x = x;    p.y = y;    p.time = 0;     Q.push(p);    while( !Q.empty() ) {        p = Q.front();  Q.pop();        if( p.x == target_x && p.y == target_y ) return p.time;        for(int i = 0; i < DIR; i ++){            if( p.x+dir[i][0] < 1 || p.x+dir[i][0] > MAX_ROW || p.y+dir[i][1] < 1 || p.y+dir[i][1] > MAX_COL ) continue ;            if( !visited[p.x+dir[i][0]][p.y+dir[i][1]] ) {                visited[p.x+dir[i][0]][p.y+dir[i][1]] = true;                Point tmp_p;                tmp_p.x = p.x+dir[i][0];                tmp_p.y = p.y+dir[i][1];                tmp_p.time = p.time + 1;                Q.push(tmp_p);            }        }    }    return -1;}int main(int argc, char const *argv[]){#ifndef ONLINE_JUDGE        freopen("test.in", "r", stdin);#endif    int x, y;    char tmp_x1, tmp_x2;    while( ~scanf(" %c%d %c%d", &tmp_x1, &y, &tmp_x2, &target_y) ) {        x = tmp_x1 - 'a' + 1;      target_x = tmp_x2 - 'a' + 1;        memset(visited, false, sizeof(visited));        printf("To get from %c%d to %c%d takes %d knight moves.\n", tmp_x1, y, tmp_x2, target_y, BFS(x, y));    }    return 0;}


原创粉丝点击