【Ybtoj 第5章 例题1】走迷宫【广搜】

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述


解题思路

这道题是一道广搜模板题。。。完。。。


代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;

string s;
const int dx[5]={
    
    0,1,-1,0,0};
const int dy[5]={
    
    0,0,0,1,-1};
int n,sx,sy,tx,ty,a[2000][2000],v[2000][2000],dis[2000000],st[2000000][3],h,t;

int bfs()
{
    
    
	int h=0,t=1;
	dis[1]=0;
	v[sx][sy]=1;
	st[1][1]=sx;
	st[1][2]=sy;
	while(h<t)
	{
    
    
		h++;
		
		for(int i=1;i<=4;i++)
		{
    
    
			int xx=st[h][1]+dx[i],yy=st[h][2]+dy[i];
			if(xx>0&&xx<=n&&yy>0&&yy<=n&&v[xx][yy]==0&&a[xx][yy]==0)
			{
    
    
				t++;
				st[t][1]=xx; 
				st[t][2]=yy;
				dis[t]=dis[h]+1;
				v[xx][yy]=1;
				if(xx==tx&&yy==ty)
				{
    
    
					printf("%d",dis[t]);
					return 0;
				}
			}
		}
	} 
}


int main()
{
    
    
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
    
    
		cin>>s;
		for(int j=0;j<n;j++)
		{
    
    
			if(s[j]=='1')
				a[i][j+1]=1;	
		}
	}
	scanf("%d%d%d%d",&sx,&sy,&tx,&ty);
	bfs();
}


猜你喜欢

转载自blog.csdn.net/kejin2019/article/details/112390820