做这道题其实我是想看看打印路径的方法,挺水的,看了网上别人的代码,打印路径基本上都是保存一下父节点,然后
打印出它的坐标,我写的是递归一下,从后面向前找到起点,找的过程有点不一样,之前没保存,而是继续上下左右的
找,估计是因为这个时间有点多,虽然在这道题上看不出来差别。。。无意中看到了盈神的博客,我做这道题将近比她晚了一年。。。
代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<queue>
int dist[10][10];
int visit[10][10];
int gra[10][10];
const int dx[4] = {-1,1,0,0};
const int dy[4] = {0,0,-1,1};
using namespace std;
struct node
{
int x,y;
};
void bfs(int x,int y)
{
int i;
queue<node>que;
memset(visit,0,sizeof(visit));
memset(dist,0,sizeof(dist));
node n1;
n1.x = x;
n1.y = y;
dist[x][y] = 0;
que.push(n1);
visit[x][y] = 1;
while(!que.empty())
{
node n1 = que.front();
que.pop();
if((n1.x == 5) && (n1.y == 5))
{
//printf("%d\n",dist[n1.x][n1.y]);
return ;
}
for(i=0; i<4; i++)
{
int xx = n1.x + dx[i];
int yy = n1.y + dy[i];
if(!visit[xx][yy] && (gra[xx][yy] == 0) && (xx >= 1) && (xx <= 5) &&(yy >= 1) && (yy <= 5))
{
visit[xx][yy] = 1;
dist[xx][yy] = dist[n1.x][n1.y] + 1;
node n2;
n2.x = xx,n2.y = yy;
que.push(n2);
}
}
}
}
void print_path(node n1,node n2)
{
int i;
if((n2.x == n1.x) && (n1.y == n2.y))
return;
for(i=0; i<4; i++)
{
int xx = n2.x + dx[i];
int yy = n2.y + dy[i];
if((dist[n2.x][n2.y] == dist[xx][yy] + 1) && visit[xx][yy])
{
node n3;
n3.x =xx,n3.y =yy;
print_path(n1,n3);
printf("(%d, %d)\n",n3.x-1,n3.y-1);
}
}
return ;
}
int main()
{
int i,j;
for(i=1; i<=5; i++)
for(j=1; j<=5; j++)
scanf("%d",&gra[i][j]);
bfs(1,1);
node n1,n2;
n1.x = 1, n1.y = 1;
n2.x = 5, n2.y = 5;
print_path(n1,n2);
printf("(4, 4)");
return 0;
}