题目大意:
题目本身是最简单的BFS,难点是记录路径
#include <iostream>
#include <queue>
#include <cstdio>
using namespace std;
struct NODE //记录现在所处节点 父亲节点 及步数
{
int x, y, step;
int prex, prey;
}node[10][10];
int a[10][10];
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
int vis[10][10];
void print(int xi,int yi)
{
if (xi == -1) return ;
int prexi = node[xi][yi].prex;
int preyi = node[xi][yi].prey;
print(prexi,preyi);
printf("(%d, %d)\n",xi,yi);
}
void BFS()
{
NODE cur;
node[0][0] = cur = {0,0,0,-1,-1};
queue <NODE> q;
q.push(cur);
vis[0][0] = 1;
while (!q.empty())
{
cur = q.front();
q.pop();
if (cur.x == 4 && cur.y == 4)
{
print(cur.x,cur.y);
return;
}
for (int i = 0; i != 4; ++i)
{
int xx = cur.x+dx[i];
int yy = cur.y+dy[i];
if (xx >= 0 && xx < 5 && yy >= 0 && yy < 5 && !vis[xx][yy] && !a[xx][yy])
{
vis[xx][yy] = 1;
node[xx][yy].step = node[cur.x][cur.y].step+1;
node[xx][yy].prex = cur.x;
node[xx][yy].prey = cur.y;
node[xx][yy].x = xx;
node[xx][yy].y = yy;
q.push(node[xx][yy]);
}
}
}
}
int main()
{
for (int i = 0; i != 5; ++i)
for (int j = 0; j != 5; ++j)
scanf("%d",&a[i][j]);
BFS();
return 0;
}