这是一道广搜题,主要难在于方向数组一个是马,一个是象,如果这个方向数组记不下来的话在纸上画一画就知道了不然只能背了
AC:
#include <bits/stdc++.h>
using namespace std;
int n,m;
bool vis[105][105];
int t[12][2]={{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-2},{-2,2},{2,2},{2,-2}};
struct node{
int x,y,step;
};
int bfs(int x,int y){
node now,pos,next;
now.x=x, now.y=y, now.step=0;
queue<node> q;
q.push(now);
while(!q.empty()){
pos = q.front();
q.pop();
if(pos.x == 1 && pos.y == 1) return pos.step;
for(int i=0; i<12; i++){
int bx = pos.x+t[i][0], by = pos.y+t[i][1];
if(bx < 0 || bx > 100 || by < 0 || by > 100) continue;
if(vis[bx][by]==1) continue;
vis[bx][by]=1;
next.x=bx; next.y=by; next.step=pos.step+1; ;
q.push(next);
}
}
}
int main(){
while(cin >> n >> m){
memset(vis,0,sizeof(vis));
vis[n][m]=1;
cout << bfs(n,m) << endl;
}
return 0;
}