这题是bfs的基础性题目,但是基础才显得很重要。
题目中的要求是输出每一个我们走过的点,所以我们每次记录下它的上一个节点是谁就行了。
但是我们因此就不能再使用队列了,我们开辟一个一维数组就行了,因为迷宫的大小是5*5的,所以我们直接开一个一维数组,然后模拟一下队列的进出就行了。
这个题比较坑的一点是它的输出圆括号里面,逗号后面有个空格,一定要输出,不然它会说,你的答案几乎正确,但是格式不对。
#include <iostream>
#include <cstring>
using namespace std;
struct Road {
int r,c;
int f;
};
const int MAXN=1000;
Road q[MAXN];
bool maze[5][5];
bool visited[5][5];
int head=0,tail=0;
int d[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
void bfs()
{
while (head<tail) {
Road front=q[head];
if (front.c==4&&front.r==4) {
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<=4&&last.c<=4&&last.c>=0) {
if (!visited[last.r][last.c]&&!maze[last.r][last.c]) {
last.f=head;
q[tail++]=last;
visited[last.r][last.c]=1;
}
}
}
head++;//head 在此加加,不会出现死循环
}
}
int main()
{
int path[30];
for (int i=0;i<5;i++) {
for (int j=0;j<5;j++) {
cin>>maze[i][j];
}
}
memset(visited,0,sizeof(visited));
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--) {
cout<<"("<<q[path[j]].r<<", "<<q[path[j]].c<<")"<<endl;
}
cout<<"("<<4<<", "<<4<<")"<<endl;
return 0;
}