框架依旧是BFS,不过本题需要输出路径,所以不能用c++自带的queue,因为那个pop之后就找不到了;应该使用一维数组来模拟一个队列,用数组中的下标来记录父节点,通过改变tail,head指针实现入队,出队的操作。
#include <iostream>
#include <algorithm>
#include <string.h>
#include <math.h>
#include <stdlib.h>
using namespace std;
struct Node {
int x,y,f;//f是父节点在数组中的下标
Node() {};
Node(int xx, int yy,int ff): x(xx),y(yy),f(ff) {
};
};
int maze[5][5];
bool flag[5][5];
Node queues[30];//一维数组模拟队列
int to[4][2] = { 0,1,1,0,0,-1,-1,0 };
bool valid(int x, int y) {
return x >= 0 && x <= 4 && y >= 0 && y <= 4&&maze[x][y]==0;
}
void output(int index) {
int path[60];
int i = 0;
while (1) {
Node n = queues[index];
path[2 * i] = n.x;
path[2 * i + 1] = n.y;
if (n.f == -1) {
break;
}
i++;
index = n.f;
}
while (i >= 0) {
printf("(%d, %d)\n", path[2 * i], path[2 * i + 1]);
i--;
}
}
int main() {
for (int i = 0;i < 5;i++) {
for (int j = 0;j < 5;j++) {
scanf("%d", &maze[i][j]);
}
}
int head, tail;
head = tail = 0;
queues[tail++] = Node(0, 0, -1);
flag[0][0] = 1;
while (head != tail) {
Node n = queues[head];
if (n.x == 4 && n.y == 4) {
output(head);
break;
}
//四周遍历
for (int k = 0;k < 4;k++) {
int x = n.x + to[k][0];
int y = n.y + to[k][1];
if (valid(x, y) && !flag[x][y]) {
Node nn = Node(x, y, head);
queues[tail++] = nn;
flag[x][y] = 1;
}
}
head++;
}
return 0;
}