学习路上的搜索bfs
作者:互联网
#include<iostream>
#include<queue>
#include<algorithm>
#include<cstring>
using namespace std;
int n,m;
struct node
{
int x;
int y;
};
struct edge
{
int x;
int y;
int s=0;
char step;
}rec[20][20];
char ditu[20][20];
int next[4][2]={1,0,0,-1,0,1,-1,0};
int book[20][20];
void bfs()
{
queue<node>q;
node begin;
begin.x =0;
begin.y =0;
book[0][0]=1;
q.push(begin);
while(!q.empty())
{
node pre=q.front();
q.pop();
for(int i=0;i<=3;i++)
{
node now;
now.x=pre.x+next[i][0];
now.y=pre.y+next[i][1];
if(now.x<0||now.y<0||now.x>n-1||now.x>m-1)
continue;
if(book[now.x][now.y]==0)
{
book[now.x][now.y]=1;
rec[now.x][now.y].x=pre.x;
rec[now.x][now.y].y=pre.y;
rec[now.x][now.y].s=rec[pre.x][pre.y].s+1;
if(i==0)
rec[now.x][now.y].step='D';
if(i==1)
rec[now.x][now.y].step='L';
if(i==2)
rec[now.x][now.y].step='R';
if(i==3)
rec[now.x][now.y].step='U';
q.push(now);
}
}
}
}
void digui(int x,int y)
{
if(x==0&&y==0)
{
return;
}
digui(rec[x][y].x,rec[x][y].y);
cout<<rec[x][y].step;
}
int main()
{
while(cin>>n>>m)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
cin>>ditu[i][j];
}
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
if (ditu[i][j] == '0')book[i][j] = 0;
else book[i][j] = 1;
}
bfs();
cout<<rec[n-1][m-1].s<<endl;
digui(n-1,m-1);
cout<<endl;
memset(ditu,0,sizeof(ditu));
}
return 0;
}
标签:pre,20,路上,int,bfs,book,搜索,rec,now 来源: https://blog.csdn.net/weixin_61675401/article/details/121478461