Sample Input
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
思路
用一个path数组来保存每一步所能走到到的位置进行标号,用于递归输出路径。例如样例中的path数组数据为(在下面)。可以清楚地了解bfs每一步是往哪个方向进行搜索的,可以更清楚了解bfs.
样例中:path数据
1 0 7 8 0
2 0 6 0 8
3 4 5 6 7
4 0 0 0 8
5 6 7 0 9
可以看出bfs的每一步的搜索方向啊。最后写个递归进行输出路径就可以了。
AC Code
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <functional>
#include <algorithm>
#include <algorithm>
#define _USE_MATH_DEFINES
using namespace std;
typedef long long ll;
const int MAXN = 10;
int mmp[MAXN][MAXN];
int path[MAXN][MAXN];
int dp[4][2] = {0,1,1,0,0,-1,-1,0};
bool vis[MAXN][MAXN];
struct node
{
int x, y;
int step;
friend bool operator < (node a, node b)
{
return a.step > b.step;
}
};
void getmap()
{
memset(mmp,0,sizeof(mmp));
for(int i=1; i<=5; i++)
{
for(int j=1; j<=5; j++)
{
scanf("%d",&mmp[i][j]);
}
}
}
void bfs()
{
int t = 0;
memset(vis,false,sizeof(vis));
memset(path,0,sizeof(path));
node st1, st2;
priority_queue<node> qu;
st1.x = 1, st1.y = 1, st1.step = 0;
vis[st1.x][st1.y] = true;
path[st1.x][st1.y] = st1.step + 1;
qu.push(st1);
while(!qu.empty())
{
st1 = qu.top();
qu.pop();
path[st1.x][st1.y] = st1.step + 1;///记录每一步能走到的位置
if(st1.x==5 && st1.y==5) break;
for(int i=0; i<4; i++)
{
st2.x = st1.x + dp[i][0];
st2.y = st1.y + dp[i][1];
if(st2.x<=5 && st2.x>=1 && st2.y<=5 && st2.y>=1 && !vis[st2.x][st2.y] && mmp[st2.x][st2.y] == 0)
{
vis[st2.x][st2.y] = true;
st2.step = st1.step + 1;
qu.push(st2);
}
}
}
// for(int i=1; i<=5; i++)
// {
// for(int j=1; j<=5; j++)
// {
// printf("%d ",path[i][j]);
// }
// printf("\n");
// }
}
void print(int x, int y)///递归输出路径
{
if(x==1 && y==1)
{
printf("(%d, %d)\n",x-1,y-1);
return ;
}
int prex = 0, prey = 0;
for(int i=0; i<4; i++)
{
prex = x + dp[i][0];
prey = y + dp[i][1];
if(prex<=5 && prex>=1 && prey<=5 && prey>=1 && path[x][y]-path[prex][prey]==1)
{
print(prex,prey);
printf("(%d, %d)\n",x-1,y-1);
}
}
}
int main()
{
getmap();
bfs();
print(5,5);
return 0;
}