题意:从起点到终点以马行走日字的方式求最短路径。。地图是8*8的二维矩阵。可以说是bfs模板题了,适合练手。。注意下vis数组每次需要memset初始化。。以及边界检测。。
代码:
#include<bits/stdc++.h>
using namespace std;
bool vis[9][9]={false};//记录入队情况
int dirx[]={-1,-2,-2,-1,1,2,2,1};//马一次移动的八个位置
int diry[]={-2,-1,1,2,2,1,-1,-2};
struct Node{
int x;
int y;
int step;
}S,T;
bool check(int x, int y){
//边界检测+是否入队过
if(x<1 || x>8 || y<1 || y>8)
return false;
if(vis[x][y]) return false;
return true;
}
int bfs(){
//经典万能bfs模板
memset(vis, false, sizeof(vis));//多组数据时每次都需要重置vis数组
queue<Node> q;
q.push(S);//起始位置入队
while(!q.empty()){
Node top = q.front();
q.pop();
if(top.x == T.x && top.y == T.y)
return top.step;//返回结果
for(int i = 0; i<8; i++){
int tx = top.x+dirx[i];
int ty = top.y+diry[i];
if(check(tx, ty)){//符合边界且没入队即可入队
Node node;
node.x = tx;
node.y = ty;
node.step = top.step+1;
q.push(node);
vis[tx][ty] = true;
}
}
}
return -1;//不能到达终点返回-1
}
int main(){
string s1,s2;
while(cin>>s1>>s2){
S.x=s1[0]-'a'+1;
S.y=s1[1]-'0';
S.step = 0;
T.x=s2[0]-'a'+1;
T.y=s2[1]-'0';
int cnt = bfs();
cout<<"To get from "<<s1<<" to "<<s2<<" takes "<<cnt<<" knight moves.\n";
}
return 0;
}