题目是中文的很好理解,很裸很水的bfs。就是答案输出方式有点麻烦。我的想法是用a = prev[i]数组记录第i个进入队列的点是由第a个进入队列的点拓展而来的。p.num代表p这个点是第p.num个进入队列的点。最后答案要倒序输出写的很丑:)。还有要注意格式:)。
#include <cstdio>
#include <queue>
using namespace std;
struct node {
int a[6][6], x, y, num;
node() {
x = 0;
num = 0;
y = 0;
}
};
node map;
int ansX[1000], size, ansY[1000];
int cnt, prev[1000], ansx[1000], ansy[1000], flag;
queue<node> q;
int main() {
for(int i = 0; i <= 4; i++)
for(int j = 0; j <= 4; j++)
scanf("%d", &map.a[i][j]);
q.push(map);
while(!q.empty()) {
cnt++;
node p = q.front();
q.pop();
ansx[cnt] = p.x;
ansy[cnt] = p.y;
prev[cnt] = p.num;
if (p.x == 4 && p.y == 4) {
flag = cnt;
break;
}
if (p.x != 4 && map.a[p.x + 1][p.y] == 0) {
p.x++;
p.num = cnt;
q.push(p);
p.x--;
}
if (p.x != 4 && map.a[p.x - 1][p.y] == 0 && p.x > 0) {
p.x--;
p.num = cnt;
q.push(p);
p.x++;
}
if (p.y != 4 && map.a[p.x][p.y + 1] == 0) {
p.y++;
p.num = cnt;
q.push(p);
p.y--;
}
if (p.y != 4 && map.a[p.x][p.y - 1] == 0 && p.y > 0) {
p.y--;
p.num = cnt;
q.push(p);
p.y++;
}
}
for (int i = cnt; i >= 0; i--) {
if (ansx[cnt] == 0 && ansy[cnt] == 0)
break;
ansX[++size] = ansx[cnt];
ansY[size] = ansy[cnt];
cnt = prev[cnt];
}
printf("(0, 0)\n");
for (int i = size; i >= 1; i--) {
printf("(%d, %d)\n", ansX[i], ansY[i]);
}
return 0;
}