TZOJ 4362: Gregory the Grasshopper
作者:互联网
|
题目大意是有一只蚂蚱在地图上的某一个点,这只蚂蚱的走法类似象棋里的马,八个方向,问你是否能走到叶子(终点)处,如果可以就输出最少步数,不行就impossible。
简单的裸BFS,设个f标记看看找没找到就行。
1 #include<bits/stdc++.h> 2 #define ll long long 3 using namespace std; 4 bool book[101][101];//标记数组,0为未走,1为走过 5 struct node{ 6 int x,y,step; 7 }; 8 node que[10001];//定义结构体数组,大小为n*m 9 int n,m,sx,sy,ex,ey,f,ans; 10 int nex[8][2] = {{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};//能走的八个方向 11 void bfs() 12 { 13 int tx,ty,head,tail;//head队首、tail队尾 14 head = tail = 1; 15 que[tail].x = sx;//对队尾/队首初始化为起点并标记 16 que[tail].y = sy; 17 que[tail].step = 0; 18 book[sx][sy] = 1; 19 tail++;//队尾向后扩充一位 20 while(head<tail) 21 { 22 for(int i=0;i<8;i++) 23 { 24 tx = nex[i][0]+que[head].x; 25 ty = nex[i][1]+que[head].y;//获取下一步坐标tx,ty 26 if(tx<1||ty<1||tx>n||ty>m)continue;//越界判断 27 if(book[tx][ty]==0)//book=0证明tx,ty未走过 28 { 29 book[tx][ty] = 1;//标记走过 30 que[tail].x = tx;//将tx,ty加入队尾 31 que[tail].y = ty; 32 que[tail].step = que[head].step+1;//队尾步长等于队首步长+1 33 tail++;//队尾扩充 34 } 35 if(tx==ex&&ty==ey)//如果是终点 36 { 37 f = 1;//f标记更新为1 38 ans = que[tail-1].step;//因为前面队尾扩充了,所以需要tail-1才能取回真正的队尾步长 39 break; 40 } 41 } 42 if(f)break;//找到终点结束循环 43 head++;//while循环的结尾让队首往后移一位 44 } 45 } 46 int main() 47 { 48 49 while(cin>>n>>m>>sx>>sy>>ex>>ey)//多组数据输入 50 { 51 f = 0;//初始化f=0默认没找到 52 ans = 0;//最少步数 53 if(sx==ex&&sy==ey){//起点即为终点 54 cout<<0<<endl; 55 continue; 56 } 57 memset(book,0,sizeof(book));//初始化标记数组 58 bfs();//广搜 59 if(f)cout<<ans<<endl; 60 else cout<<"impossible"<<endl; 61 } 62 return 0; 63 }
标签:队尾,tx,ty,Grasshopper,tail,que,TZOJ,Gregory 来源: https://www.cnblogs.com/jyssh/p/16381716.html