版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39562952/article/details/82701833
思路:正常bfs搜索,然后记录每个点的父节点,最后找父节点,最后输出路径;
代码如下:
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <cstring>
#include <climits>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stdio.h>
#define inf 429496729
using namespace std;
int then[4][2] = { {-1,0},{0,-1},{0,1},{1,0} };
struct fnode
{
int x;
int y;
}ans[100];
struct node
{
int val;
fnode ff;
int x;
int y;
int step;
}ma[5][5];
bool maa[5][5];//记录有没有走过
int main()
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
cin >> ma[i][j].val;
ma[i][j].x = i;
ma[i][j].y = j;
}
}
queue<node>q;
ma[0][0].step = 0;
maa[0][0] = true;
q.push(ma[0][0]);
int flag = 0;
while (!flag)
{
for (int i = 0; i < 4; i++)
{
int xx, yy;
xx = q.front().x + then[i][0];
yy = q.front().y + then[i][1];
if (xx >= 5 || yy >= 5 || xx < 0 || yy < 0 || ma[xx][yy].val == 1 || maa[xx][yy]== true)
continue;
ma[xx][yy].step = ma[q.front().x][q.front().y].step+1;
maa[xx][yy] = true;
q.push(ma[xx][yy]);
ma[xx][yy].ff.x = q.front().x;
ma[xx][yy].ff.y = q.front().y;
if (xx == 4 && yy == 4)
{
flag = 1;
int ans_count = 0;
fnode t;
t.x = xx;
t.y = yy;
while (1)
{
ans[ans_count].x = t.x;
ans[ans_count].y = t.y;
ans_count++;
if (t.x == 0 && t.y == 0)
break;
t = ma[t.x][t.y].ff;
}
for (int i = ans_count - 1; i >= 0; i--)
{
printf("(%d, %d)\n", ans[i].x, ans[i].y);
}
}
}
q.pop();
}
system("pause");
return 0;
}