Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 11410 | Accepted: 6423 |
Description
Of course you know that it is vice versa. So you offer him to write a program that solves the "difficult" part.
Your job is to write a program that takes two squares a and b as input and then determines the number of knight moves on a shortest route from a to b.
Input
Output
Sample Input
e2 e4 a1 b2 b2 c3 a1 h8 a1 h7 h8 a1 b1 c3 f6 f6
Sample Output
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 <fstream> #include <stdio.h> #include <iostream> #include <string.h> #include <string> #include <limits.h> #include <algorithm> #include <math.h> #include <numeric> #include <functional> #include <ctype.h> #include<queue> using namespace std; int dir[8][2] = {{2,1},{-2,1},{1,2},{1,-2},{2,-1},{-1,2},{-1,-2},{-2,-1}}; int visit[19][19]; string str1, str2; queue<char> gg; int bfs(char one, char two, int cou){ gg.push(one); gg.push(two); gg.push(cou) visit[one-'a'+1][two-'1'+1] = 1; //cout<<one-'a'+1<<endl; while(!gg.empty()){ char x1 = gg.front(); gg.pop(); char y1 = gg.front(); gg.pop(); for(int i = 0; i< 8;i++){ char neo = x1 + dir[i][0]; char net = y1 + dir[i][1]; if(neo == str2[0] && net == str2[1]){ //cout<<cou<<endl; return 0; } if(neo <= 'h' && neo >= 'a' && net <= '8' && net >= '1' && !visit[neo-'a'+1][net-'1'+1] ){ gg.push(neo); gg.push(net); visit[neo-'a'+1][net-'1'+1] = 1; cou++; } } } } int main(){ while(cin>>str1>>str2){ memset(visit,0,sizeof(visit)); int cou = 0; for(int i = 0;!gg.empty();){ gg.pop(); } bfs(str1[0],str1[1],cou); cout<<cou<<endl; } return 0; }