您的位置:首页 > 其它

宽度优先搜索 最短路径

2017-11-20 21:17 281 查看
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<map>
#include<queue>
#include<set>
#define maxn 105
#define LL long long
#define lson step<<1
#define rson step<<1|1
#define INF 4294967295
using namespace std;
int n,m;
int sx,sy,gx,gy;
struct node
{
int x,y,s;//s为路径长度
};
char mapp[maxn][maxn];
bool book[maxn][maxn];
void input()
{
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>mapp[i][j];
}
}
}
void bfs(int sx,int sy,int gx,int gy)
{
int next[4][2]={{0,1},{1,0},{-1,0},{0,-1}};
int tx,ty;
node h,fw;
h.x=sx;h.y=sy;h.s=0;
queue<node>q;
q.push(h);
int flag=0;
while(!q.empty())
{
h=q.front();
q.pop();
for(int k=0;k<4;k++)
{
tx=h.x+next[k][0];
ty=h.y+next[k][1];
if(tx<0||tx>=n||ty<0||ty>=m)
continue;
if(mapp[tx][ty]=='.'&&book[tx][ty]==false)
{
fw.x=tx;
fw.y=ty;
fw.s=h.s+1;
book[tx][ty]=true;
q.push(fw);
}
if(tx==gx&&ty==gy)
{
flag=1;
break;
}
}
if(flag)
break;
}
cout << fw.s << endl;
}
int main()
{
ios_base::sync_with_stdio(false);
cin>>n>>m;
input();
memset(book,false,sizeof(book));
cin>>sx>>sy>>gx>>gy;
sx--;sy--;gx--;gy--;
bfs(sx,sy,gx,gy);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: