杭电 1372题
//朴素的广度优先搜索
#include <iostream>
#include <string>
using namespace std;
#define arraysize 10
typedef struct node
{
int col;
int row;
int step; //记录该点到原点的距离
}node;
node myqueue[100];
bool hash[arraysize][arraysize]; //记录该点是否加入到队列中
int dir[8][2]={{2,1},{2,-1},{1,-2},{1,2},{-1,-2},{-1,2},{-2,1},{-2,-1}}; //代表骑士遍历的8个方向
int si,sj,ei,ej; //起点,终点
string str1,str2;
void BFS()
{
int i,j;
int start = 0;
int end = 1;
memset(hash,0,sizeof(hash)); //初始化
node frontnode,next;
myqueue[0].col = si;
myqueue[0].row = sj;
myqueue[0].step = 0;
if(si==ei && sj == ej) //此处别忘了进行判断起点和终点在同一点
{
cout<<"To get from "<<str1<<" to "<<str2<<" "<<"takes "<<0<<" knight moves."<<endl;
return;
}
hash[si][sj] = true; //标识起点加入到队列中
while(end!=start)
{
frontnode = myqueue[start];
start++; //删除头部节点
for(i=0;i<8;++i) //进行8个方向的遍历
{
next.col = frontnode.col + dir[i][0];
next.row = frontnode.row + dir[i][1];
next.step = frontnode.step+1;
if(next.col == ei && next.row == ej)
{
cout<<"To get from "<<str1<<" to "<<str2<<" "<<"takes "<<next.step<<" knight moves."<<endl;
return;
}
if(next.col >=0 && next.col<8 && next.row>=0 && next.row <8 && !hash[next.col][next.row])
{
myqueue[end] = next;
end++;
hash[next.col][next.row] = true; //标识该点加入到队列中
}
}
}
}
int main()
{
//freopen("1.txt","r",stdin);
while(cin>>str1>>str2)
{
si = str1[0]-97; //列从0开始,将字符转化为整数,a的ASCII码97
sj = str1[1]-'1';//行也从0开始,将字符整数转化为整数
ei = str2[0]-97;
ej = str2[1]-'1';
BFS();
}
return 0;
}