[Ybtoj High-Efficiency Advanced 1.5] A. Walk the maze [Wide Search]

Insert picture description here

analysis

Search templates widely and pay attention to entering and leaving the team.

Upload code

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;

char a[1001][1001];
int qx[1000001],qy[1000001];
int n,t,h,sx,sy,ex,ey;
int p[1001][1001],f[1001][1001];
int dx[5]={
    
    0,1,0,-1,0};
int dy[5]={
    
    0,0,1,0,-1};

int main()
{
    
    
	cin>>n;
	for(int i=1;i<=n;i++)
	{
    
    
		for(int j=1;j<=n;j++)
		{
    
    
			cin>>a[i][j];
		}
	}
	cin>>sx>>sy>>ex>>ey;
	qx[1]=sx;
	qy[1]=sy;
	t=1;
	p[sx][sy]=1;
	while(h<=t)
	{
    
    
		h++;
		for(int i=1;i<=4;i++)
		{
    
    
			int xx=qx[h]+dx[i],yy=qy[h]+dy[i];
			if(!p[xx][yy]&&xx>0&&xx<=n&&yy>0&&yy<=n&&a[xx][yy]=='0')
			{
    
    
				f[xx][yy]=f[qx[h]][qy[h]]+1;
				if(xx==ex&&yy==ey)
				{
    
    
					cout<<f[xx][yy]<<endl;
					return 0;
				}
				p[xx][yy]=1;
				t++;
				qx[t]=xx;
				qy[t]=yy;
			}
		}
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/dglyr/article/details/112976688