题解2
2024-06-08 10:23:15
发布于:广东
53阅读
0回复
0点赞
#include<bits/stdc++.h>
#include<queue>
using namespace std;
long long n,m,sx,sy,ex,ey;
char a[9999][9999];
struct node{
	int x;
	int y;
	int t;
}r,l;
bool vis[9999][9999];
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
int main(){
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			cin>>a[i][j];
			if(a[i][j]=='@'){
				sx=i;
				sy=j;
			}
			if(a[i][j]=='*'){
				ex=i;
				ey=j;
			}
		}
	}
	queue<node> q;
	q.push({sx,sy,0});
	vis[sx][sy]=1;
	while(!q.empty()){
		r=q.front();
		q.pop();
		if(r.x==ex && r.y==ey){
			cout<<r.t;
			return 0;
		}
		for(int i=0;i<4;i++){
			l.x=r.x+dx[i];
			l.y=r.y+dy[i];
			l.t=r.t+1;
			if(l.x>=1 && l.x<=n && l.y>=1 && l.y<=m && a[l.x][l.y]!='#' && !vis[l.x][l.y]){
				q.push(l);
				vis[l.x][l.y]=1;
			}
		}
	}
	cout<<-1;
	return 0;
}
这里空空如也




有帮助,赞一个