您的位置:首页 > 其它

BFS和DFS记录路径

2015-08-02 10:12 567 查看
 DFS记录路径的意义好像不大,因为不一定是最短的,但是实现起来却很简单。

#include<math.h>
#include<stdio.h>
#include<queue>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define N 1234

int n,m,step;
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
char mat

;
int  vis

;
int    a[2]
;

void dfs(int x,int y,int t)
{
if(step!=-1)return;
if(x<1||x>n||y<1||y>m)return;
if(mat[x][y]=='#'||vis[x][y])return;
if(mat[x][y]=='r')
{
step=t;
a[0][t]=x;
a[1][t]=y;
return ;

}
vis[x][y]=1;
//    printf("(%d,%d)\n",x,y);
a[0][t]=x;
a[1][t]=y;
for(int i=0;i<4;i++)
dfs(x+dx[i],y+dy[i],t+1);
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
int stx,sty;
step=-1;
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
scanf(" %c",&mat[i][j]);
if(mat[i][j]=='a')
stx=i,sty=j;
}
dfs(stx,sty,0);
if(step==-1)puts("Poor ANGEL has to stay in the prison all his life.");
else
{
cout<<step<<endl;
puts("Path");
for(int i=0;i<=step;i++)
printf("%d,%d\n",a[0][i],a[1][i]);
}

}
return 0;
}

/*

7 8
#.#####.
#.a#..r.
#..#....
..#..#.#
#...##..
.#......
........
*/


BFS记录路径:我的方法是每一个点都保存一下它从哪个方向走过来的(也就是那个i),这样由最后一个点,就可以倒推出倒数第二个点,倒数第二个点再可以推出倒数第三个点,最后推到起点,再反过来,就是路径了。

#include<math.h>
#include<stdio.h>
#include<queue>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define N 1234
struct point
{
int x,y,t,dir;
}st;

int n,m,step;
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
char mat

;
int  vis

;
int  xx
;
int  yy
;
int  d

;

int bfs()
{
queue<point>q;
q.push(st);vis[st.x][st.y]=1;
while(!q.empty())
{
point cur=q.front();
q.pop();
for(int i=0;i<4;i++)
{
point next=cur;
next.x+=dx[i];next.y+=dy[i];

if(next.x<1||next.x>n||next.y<1||next.y>m)continue;
if(mat[next.x][next.y]=='#'||vis[next.x][next.y]==1)continue;

d[next.x][next.y]=i;

if(mat[next.x][next.y]=='.')next.t=next.t+1;
if(mat[next.x][next.y]=='r')
{
xx[0]=next.x;
yy[0]=next.y;
step=next.t+1;
return step;
}
q.push(next);vis[next.x][next.y]=1;
}
}
return -1;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
step=0;
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
scanf(" %c",&mat[i][j]);
if(mat[i][j]=='a')
st.x=i,st.y=j,st.t=0;
}
int ans=bfs();
if(ans==-1)puts("Poor ANGEL has to stay in the prison all his life.");
else
{
cout<<ans<<endl;

for(int i=1;i<=step;i++)
{
xx[i]=xx[i-1] - dx[ d[ xx[i-1] ][ yy[i-1] ] ];
yy[i]=yy[i-1] - dy[ d[ xx[i-1] ][ yy[i-1] ] ];
}
puts("Path");
for(int i=step;i>=0;i--)
{
printf("%d,%d\n",xx[i],yy[i]);
}
}

}
return 0;
}

/*

7 8
#.#####.
#.a#..r.
#..#....
..#..#.#
#...##..
.#......
........

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: