http://hncu.acmclub.com/index.php?app=problem_title&id=111&problem_id=1101
小明很喜欢下国际象棋,一天,他拿着国际象棋中的“马”时突然想到一个问题:
给定两个棋盘上的方格a和b,马从a跳到b最少需要多少步?
现请你编程解决这个问题。
提示:国际象棋棋盘为8格*8格,马的走子规则为,每步棋先横走或直走一格,然后再往外斜走一格。
输入包含多组测试数据。每组输入由两个方格组成,每个方格包含一个小写字母(a~h),表示棋盘的列号,和一个整数(1~8),表示棋盘的行号。
对于每组输入,输出一行“To get from xx to yy takes n knight moves.”。
e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6
To get from e2 to e4 takes 2 knight moves.
To get from a1 to b2 takes 4 knight moves.
To get from b2 to c3 takes 2 knight moves.
To get from a1 to h8 takes 6 knight moves.
To get from a1 to h7 takes 5 knight moves.
To get from h8 to a1 takes 6 knight moves.
To get from b1 to c3 takes 1 knight moves.
To get from f6 to f6 takes 0 knight moves.
思路:
简单的BFS,只要弄清楚马的走法就可以了,一开始字符数组开小了,蛋疼,以后果断要大方点啊
#include <stdio.h> #include <queue> #include <string.h> using namespace std; struct node { int x,y,step; }; int vis[8][8]; int sx,sy,ex,ey,ans; int to[8][2]={-1,-2,-2,-1,-2,1,-1,2,1,2,2,1,2,-1,1,-2}; int check(int x,int y) { if(x<0 || y<0 || x>=8 || y>=8) return 1; if(vis[x][y]) return 1; return 0; } void bfs() { int i; queue<node> Q; node a,next; a.x = sx; a.y = sy; a.step = 0; vis[sx][sy] = 1; Q.push(a); while(!Q.empty()) { a = Q.front(); Q.pop(); if(a.x == ex && a.y == ey) { ans = a.step; return ; } for(i = 0;i<8;i++) { next = a; next.x+=to[i][0]; next.y+=to[i][1]; if(check(next.x,next.y)) continue; next.step = a.step+1; vis[next.x][next.y] = 1; Q.push(next); } } return ; } int main() { char ch1[10],ch2[10]; while(~scanf("%s%s",ch1,ch2)) { sx = ch1[0]-'a'; sy = ch1[1]-'1'; ex = ch2[0]-'a'; ey = ch2[1]-'1'; memset(vis,0,sizeof(vis)); bfs(); printf("To get from %s to %s takes %d knight moves.\n",ch1,ch2,ans); } return 0; }