#include<cstdio> structRoad { int r,c; int f; }; constint MAXN=1001; Road q[MAXN];//队列 int head=0,tail=0; bool maze[5][5];//迷宫 bool visited[5][5];//是否被访问过 int d[4][2]={{1,0},{-1,0},{0,1},{0,-1}};//方向 int m,n; int startx,starty,endx,endy;
voidbfs(){ while (head<tail) { Road front=q[head];//保存队头 if (front.c==endx&&front.r==endy) { //达到终点退出循环 break; } for (int i=0;i<4;i++) { Road last; last.r=front.r+d[i][0]; last.c=front.c+d[i][1]; if (last.r>=0&&last.r<m&&last.c<n&&last.c>=0) { if (!visited[last.r][last.c]&&!maze[last.r][last.c]) { last.f=head;//记录入队前head值方便之后打印路径 q[tail++]=last;//入队 visited[last.r][last.c]=true;//已经访问,做上标记 } } } //出队 head++; } }
intmain(){ int path[30]; scanf("%d%d%d%d%d%d",&m,&n,&startx,&starty,&endx,&endy); for (int i=0;i<5;i++) { for (int j=0;j<5;j++) { scanf("%d",&maze[i][j]); } } Road a={0,0,-1}; q[tail++]=a; visited[0][0]=1; bfs(); int i=0; while (q[head].f>=0) { path[i++]=q[head].f; head=path[i-1]; } for (int j=i-1;j>=0;j--) { printf("(%d, %d)\n",q[path[j]].r,q[path[j]].c); } printf("(%d, %d)",endx,endy); return0; }