AcWing 1101. 献给阿尔吉侬的花束

输入样例:

3
3 4
.S..
###.
..E.
3 4
.S..
.E..
....
3 4
.S..
####
..E.

输出样例:

5
1
oop!

 vis标记的修改,要在添加到队列前,不要在出队列后,否则会重复路过某地点。

#include<bits/stdc++.h>
using namespace std;
const int N=200+5;
int t,n,m,sx,sy,ex,ey;
char ch[N][N];
int vis[N][N];
struct node{
	int x,y,w;
};
int dir[4][2]={1,0,0,1,-1,0,0,-1};
int check(int x,int y){
	return x>0&&y>0&&x<=n&&y<=m;
}
void bfs(){
	memset(vis,0,sizeof vis);
	queue<node>q;
	node start={sx,sy,0};
	node next;
	vis[start.x][start.y]=1;
	q.push(start);
	while(q.size()){
		start=q.front();
		q.pop();
		if(start.x==ex&&start.y==ey){
			cout<<start.w<<endl;
			return;
		}
		for(int i=0;i<4;i++){
			next.x=start.x+dir[i][0];
			next.y=start.y+dir[i][1];
			if(check(next.x,next.y)&&ch[next.x][next.y]!='#'&&!vis[next.x][next.y]){
				next.w=start.w+1;
				vis[next.x][next.y]=1;
				q.push(next);
			}
		}
	}
	cout<<"oop!"<<endl;
}
int main(){
	scanf("%d",&t);
	while(t--){
		scanf("%d%d",&n,&m);
		for(int i=1;i<=n;i++){
			for(int j=1;j<=m;j++){
				cin>>ch[i][j];
				if(ch[i][j]=='S') sx=i,sy=j;
				else if(ch[i][j]=='E') ex=i,ey=j;
			}
		}
		bfs();
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值