http://acm.hdu.edu.cn/showproblem.php?pid=1372
BFS
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string.h>
#include <vector>
#include <queue>
#include <set>
#define MAXN 100000+5
#define MAX 200000
using namespace std;
struct Point{
int x,y;
int step;
bool operator==(const Point p) const{
if(x==p.x&&y==p.y) return true;
return false;
}
};
int d[8][2]={{1,2},{1,-2},{2,1},{2,-1},{-1,2},{-1,-2},{-2,1},{-2,-1}};
Point st,ed;
bool vis[10][10];
bool legal(Point p){
if(!vis[p.x][p.y]&&p.x>0&&p.x<9&&p.y>0&&p.y<9)
return true;
return false;
}
int bfs(){
queue<Point>q;
q.push(st);
while(!q.empty()){
Point temp,cur;
cur=q.front();
q.pop();
if(cur==ed) return cur.step;
for(int i=0;i<8;i++){
temp.x=cur.x+d[i][0];
temp.y=cur.y+d[i][1];
if(legal(temp)){
temp.step=cur.step+1;
q.push(temp);
}//if
}//for
}//while
}
int main(){
char s1[4],s2[4];
while(scanf("%s %s",s1,s2)!=EOF){
// printf("%s%s\n",s1,s2);
memset(vis,0,sizeof(vis));
st.x=s1[0]-'a'+1;
st.y=s1[1]-'0';
st.step=0;
ed.x=s2[0]-'a'+1;
ed.y=s2[1]-'0';
int ans=bfs();
printf("To get from %s to %s takes %d knight moves.\n",s1,s2,ans);
}
return 0;
}
#include <stdio.h>
#include <string.h>
int knight[8][8];
int x[8]={1,1,2,2,-1,-1,-2,-2};
int y[8]={2,-2,1,-1,2,-2,1,-1};//8个方向
void dfs(int si,int sj,int moves)
{
if(si < 0 || sj < 0 || si >7 || sj >7 || moves >= knight[si][sj])
return;
knight[si][sj] = moves;
int i;
for(i = 0; i < 8; i++)
dfs(si + x[i],sj + y[i],moves + 1);
}
int main()
{
char a[5],b[5];
while(scanf("%s%s",a,b) != EOF)
{
memset(knight,10,sizeof(knight));
dfs(a[0] - 'a',a[1] - '1',0);
printf("To get from %s to %s takes %d knight moves.\n",a,b,knight[b[0] - 'a'][b[1] - '1']);
}
return 0;
}