其实就是bfs。
#include <iostream>
#include <bits/stdc++.h>
#define maxn 9
using namespace std;
struct Node
{
int r,c;
Node(int i,int j):r(i),c(j){}
Node(){}
};
int maze[maxn][maxn];
int r1,c1,r2,c2;
int dc[8] = {-2,-1,1,2,2,1,-1,-2};
int dr[8] = {1,2,2,1,-1,-2,-2,-1};
bool vis[maxn][maxn];
Node p[maxn][maxn];
bool bound(int r,int c)
{
return r>=0&&r<8&&c>=0&&c<8;
}
void BFS(Node u)
{
int r,c;
queue<Node>q;
Node w;
q.push(u);
vis[u.r][u.c] = 1;
while(!q.empty())
{
Node v = q.front();q.pop();
if(v.r == r2 && v.c == c2)
{
return;
}
for(int i = 0;i<8;i++)
{
r=v.r+dr[i];
c=v.c+dc[i];
if(!vis[r][c]&&bound(r,c))
{
vis[r][c] = 1;
w = Node(r,c);
p[r][c] = v;
q.push(w);
}
}
}
}
int main()
{
string s1,s2;
Node u;
int r,c;
int ans;
while(cin>>s1&&cin>>s2)
{
ans = 0;
memset(maze,0,sizeof(maze));
memset(vis,0,sizeof(vis));
memset(p,0,sizeof(p));
c1 = s1[0]-'a';r1 = s1[1]-'1';
c2 = s2[0]-'a';r2 = s2[1]-'1';
maze[r1][c1] = 1;maze[r2][c2] = 1;
BFS(Node(r1,c1));
r = r2;c = c2;
while(!(r==r1 && c == c1))
{
ans++;
u = p[r][c];
r = u.r;c = u.c;
}
cout<<"To get from "<<s1<<" to "<<s2<<" takes "<<ans<<" knight moves."<<endl;
}
return 0;
}
/**
e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6
**/