题解: 用一个结构体二维数组来存每个点的上一个点的坐标,通过递归到达起点,在回溯时打印路径
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int mp[5][5];
bool vis[5][5];
int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
struct node
{int x, y;
}Step[5][5];;
void bfs()
{memset(vis, 0, sizeof(vis));node S, E;S.x = 0, S.y = 0;E.x = 4, E.y = 4;queue<node> q;q.push(S);while(!q.empty()){node now = q.front();if(now.x == E.x && now.y == E.y){return;}q.pop();node next;for(int i = 0; i < 4; i++){next.x = now.x + dir[i][0];next.y = now.y + dir[i][1];if(next.x < 5 && next.x >= 0 && next.y < 5 && next.y >= 0 && !vis[next.x][next.y] && mp[next.x][next.y] != 1){Step[next.x][next.y].x = now.x;Step[next.x][next.y].y = now.y;vis[next.x][next.y] = true;q.push(next);}}}
}
void print(int x, int y)
{if(x == 0 && y == 0){printf("(0, 0)\n");return;}print(Step[x][y].x, Step[x][y].y);printf("(%d, %d)\n", x, y);
}
int main()
{memset(mp, 0, sizeof(mp));for (int i = 0; i < 5; i++)for (int j = 0; j < 5; j++)cin >> mp[i][j];bfs();print(4, 4);
}