多吃点儿


私信TA

用户名:2021984130518

访问量:438

签 名:

等  级
排  名 254
经  验 5805
参赛次数 5
文章发表 13
年  龄 0
在职情况 学生
学  校
专  业

  自我简介:

解题思路:

注意事项:

参考代码:

#include <iostream>
#include <queue>
using namespace std;
struct node{
	int x;
	int y;
	int step;
	node(int xx,int yy,int sstep){
		x=xx;
		y=yy;
		step=sstep;
	}
};
char s[101][101];
int sx,sy,fx,fy;//起点和终点的横纵坐标
bool vis[101][101];
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
int n,m;
bool in(int x,int y){
	return x>=0&&x<n&&y>=0&&y<m;
}
int bfs(int x,int y){
	queue<node> q;
	q.push(node(x,y,0));
	while(!q.empty()){
		node a=q.front();
		q.pop();
		int x=a.x,y=a.y;
		for(int i=0;i<4;i++){
			int tx=x+dir[i][0];
			int ty=y+dir[i][1];
			int tstep=a.step+1;
			if(in(tx,ty)&&!vis[tx][ty]&&s[tx][ty]=='-'){
				vis[tx][ty]=true;
				q.push(node(tx,ty,tstep));
			}
			if(tx==fx&&ty==fy){
				return a.step+1;
			}
		}
	}
	return -1;
}
int main(){
	int t;
	scanf("%d",&t);
	while(t--){
		scanf("%d%d",&n,&m);
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				cin>>s[i][j];
				if(s[i][j]=='S'){
					sx=i,sy=j;
				}else if(s[i][j]=='E'){
					fx=i,fy=j;
				}
			}
		}
		cout<<bfs(sx,sy)<<endl;
	}
	return 0;
}


 

0.0分

0 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区