宽度优先搜索 最短路径

#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;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值