您的位置:首页 > 其它

算法提高 学霸的迷宫

2018-03-02 20:54 218 查看
这道题是BFS搜索的一道经典题目,我用一个结构体保存坐标,离原点的距离,路径。每次符合条件的点压入队列里,四个方向里先到的点被标记上,之后再到的点距离更远,就不能被标记了。尤其注意上下左右对应的是矩阵的行和列,与坐标方向不一样。
源代码:#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<string>
#include<queue>
using namespace std;
struct point
{
int x,y,d;
string s;
};
char mp[550][550];
int vis[550][550];
int n,m;
int dir[4][2] = {{1,0},{0,-1},{0,1},{-1,0}};
char dic[4] = {'D','L','R','U'};
queue<point>q;
void bfs()
{
point a;
a.x = 0;a.y = 0;a.s = "";a.d = 0;
q.push(a);
vis[0][0] = 1;
while(!q.empty())
{
point p = q.front();
if(p.x == n - 1 && p.y == m - 1)
{
cout<<p.d<<endl;
cout<<p.s<<endl;
break;
}
q.pop();
for(int i = 0; i < 4; i++)
{
int xx = p.x + dir[i][0];
int yy = p.y + dir[i][1];
if(xx >= 0 && xx < n && yy >= 0 && yy < m && !vis[xx][yy] && mp[xx][yy] != '1')
{
point tmp;
tmp.x = xx;
tmp.y = yy;
tmp.s = p.s + dic[i];
tmp.d = p.d + 1;
vis[xx][yy] = 1;
q.push(tmp);
}
}
}
}
int main()
{

cin>>n>>m;
for(int i = 0; i < n; i++)
scanf("%s",mp[i]);
bfs();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: