1.题面
http://poj.org/problem?id=1915
2.解题思路
又是一道bfs搜索的题目,而且很基础,利用队列先进先出的性质实现bfs就好,然后ACM和PAT不一样的地方时,数据量会比较大,从前做PAT的时候,每组数据我都会使用新建立的队列,并且基本不做什么剪枝,但是ACM这样做会爆空间,正确的做法是每次都使用同一个队列,最好干脆不适用STL库中提供的队列,自己模拟就好。
3.解题代码
/*****************************************************************
> File Name: tmp.cpp
> Author: Uncle_Sugar
> Mail: uncle_sugar@qq.com
> Created Time: 2016年02月18日 星期四 15时07分56秒
****************************************************************/
# include <cstdio>
# include <cstring>
# include <cmath>
# include <cstdlib>
# include <iostream>
# include <iomanip>
# include <set>
# include <map>
# include <vector>
# include <stack>
using namespace std;
const int debug = 0;
const int size = 300 + 10;
typedef long long ll;
struct coord{
int x,y,step;
coord(){}
coord(int _x,int _y,int _step):x(_x),y(_y),step(_step){}
};
int dx[8] = {1,2,-1,-2,1,2,-1,-2};
int dy[8] = {2,1,-2,-1,-2,-1,2,1};
int g[size][size];
coord queue[size*size];
int s_que=0,e_que=0;
int n;
bool inrange(int tx,int ty){
return tx<n&&tx>=0&&ty<n&&ty>=0;
}
int main()
{
std::ios::sync_with_stdio(false);cin.tie(0);
int i,j,k;
int T;
cin >> T;
while (T--){
cin >> n;
memset(g,0,sizeof(g));
s_que = e_que = 0;
int sx,sy;
int ex,ey;
cin >> sx >> sy;
cin >> ex >> ey;
g[sx][sy] = 1;
queue[e_que] = coord(sx,sy,0);e_que++;
int ans = 0;
while (g[ex][ey]==0&&s_que<e_que){
coord T = queue[s_que];s_que++;if (debug) cout << "gets "<< T.x << ' ' << T.y << endl;
for (i=0;i<8;i++){
int tx = T.x + dx[i];
int ty = T.y + dy[i];if (debug) cout << "gets tx ty "<< tx << ' ' << ty << endl;
int tstep = T.step + 1;
if (tx==ex&&ty==ey){
g[tx][ty] = 1;ans = tstep;
break;
}if (debug) cout << "range " << inrange(tx,ty) << ' ' << g[tx][ty] << endl;
if (inrange(tx,ty)&&g[tx][ty]==0){
g[tx][ty] = 1;
queue[e_que] = coord(tx,ty,tstep);e_que++;
}
}
if (g[ex][ey]==1)
break;
}
if (g[ex][ey]==1)
cout << ans << '\n';
else
cout << "error!" << endl;
}
return 0;
}