/**
* poj1915 BFS
* 乍一看以为是DP,想了半天也没有想出一个特别好的dp方案来,果然还是走BFS吧
* 做法比较简单粗暴了,代码也很粗暴,就是宽搜,从最初始点开始,8种方向只要能走就走一步,只要这个点还没有走过,就将其作为新的出现的点记录下来
* 依照步数从小往大升序地遍历,得到的一定是最小值
*/
#include <cstdio>
#include <cstring>
const int MAX_NUM = 301;
struct point{
int x;
int y;
int step;
} p[MAX_NUM*MAX_NUM];
bool flag[MAX_NUM][MAX_NUM];
int l;
int father,child;
int xstart,xend,ystart,yend;
void bfs(){
father = 0;
child = 1;
p[0].x = xstart;
p[0].y = ystart;
p[0].step = 0;
flag[xstart][ystart] = true;
int x,y,step;
if(xstart == xend && ystart == yend){
printf("0\n");
return;
}
while(1){
x = p[father].x;
y = p[father].y;
step = p[father].step;
//x-2 y-1
if(x>=2 && y>=1){
if(!flag[x-2][y-1]){
flag[x-2][y-1] = true;
p[child].x = x-2;
p[child].y = y-1;
p[child].step = step+1;
if(p[child].x == xend && p[child].y == yend){
break;
}
++child;
}
}
//x-2 y+1
if(x>=2 && y<l-1){
if(!flag[x-2][y+1]){
flag[x-2][y+1] = true;
p[child].x = x-2;
p[child].y = y+1;
p[child].step = step+1;
if(p[child].x == xend && p[child].y == yend){
break;
}
++child;
}
}
//x-1 y+2
if(x>=1 && y<l-2){
if(!flag[x-1][y+2]){
flag[x-1][y+2] = true;
p[child].x = x-1;
p[child].y = y+2;
p[child].step = step+1;
if(p[child].x == xend && p[child].y == yend){
break;
}
++child;
}
}
//x-1 y-2
if(x>=1 && y>=2){
if(!flag[x-1][y-2]){
flag[x-1][y-2] = true;
p[child].x = x-1;
p[child].y = y-2;
p[child].step = step+1;
if(p[child].x == xend && p[child].y == yend){
break;
}
++child;
}
}
//x+1 y-2
if(x<l-1 && y>=2){
if(!flag[x+1][y-2]){
flag[x+1][y-2] = true;
p[child].x = x+1;
p[child].y = y-2;
p[child].step = step+1;
if(p[child].x == xend && p[child].y == yend){
break;
}
++child;
}
}
//x+1 y+2
if(x<l-1 && y<l-2){
if(!flag[x+1][y+2]){
flag[x+1][y+2] = true;
p[child].x = x+1;
p[child].y = y+2;
p[child].step = step+1;
if(p[child].x == xend && p[child].y == yend){
break;
}
++child;
}
}
//x+2 y-1
if(x<l-2 && y>=1){
if(!flag[x+2][y-1]){
flag[x+2][y-1] = true;
p[child].x = x+2;
p[child].y = y-1;
p[child].step = step+1;
if(p[child].x == xend && p[child].y == yend){
break;
}
++child;
}
}
//x+2 y+1
if(x<l-2 && y<l-1){
if(!flag[x+2][y+1]){
flag[x+2][y+1] = true;
p[child].x = x+2;
p[child].y = y+1;
p[child].step = step+1;
if(p[child].x == xend && p[child].y == yend){
break;
}
++child;
}
}
++father;
}
printf("%d\n",p[child].step);
}
int main(){
int t;
scanf("%d",&t);
while(t--){
scanf("%d",&l);
scanf("%d%d%d%d",&xstart,&ystart,&xend,¥d);
for(int i=0;i<l;++i){
memset(flag[i],0,sizeof(flag[i]));
}
bfs();
}
return 0;
}
poj1915 BFS
最新推荐文章于 2020-02-16 23:37:55 发布