【队列】C++队列头文件<queue>的应用


 

Description

Given a maze, find a shortest path from start to goal.

 

Input

Input consists serveral test cases.

First line of the input contains number of test case T.

For each test case the first line contains two integers N , M ( 1 <= N, M <= 100 ).

Each of the following N lines contain M characters. Each character means a cell of the map.

Here is the definition for chracter.

 

Constraint:

  • For a character in the map:     
    • 'S' : start cell
    • 'E' : goal cell
    • '-' : empty cell
    • '#' :  obstacle cell
  • no two start cell exists.
  • no two goal cell exists.

 

Output

For each test case print one line containing shortest path. If there exists no path from start to goal, print -1.

 

Sample Input

1
5 5
S-###
-----
##---
E#---
---##

Sample Output

9

 

 

//BFS 广度优先搜索

#include<stdio.h>
#include<queue>
using namespace std;

int vis[110][110];
int dir[4][2]={0,1,1,0,-1,0,0,-1};
char c[110][110];
int w,h,t;

struct list{
	int x,y;
	int step;
}a;

int mini=0;

queue<list> que; //定义队列

//que.push(a);					队尾进队列,a为进队列元素
//que.pop();					队首出队列
//list temp=que.front();		队首的元素
//int size=que.size();			元素个数
//while(!que.empty())que.pop();	重复使用时,初始化清空队列



int BFS(struct list a){
	while(!que.empty()) que.pop();
	list now,temp;
	que.push(a);
	int i;
	while(!que.empty()){
		now=que.front();
		que.pop();
		for(i=0;i<4;++i){
			temp.x=now.x+dir[i][0];
			temp.y=now.y+dir[i][1];
			temp.step=now.step+1;
			if(vis[temp.x][temp.y]==0){
				if(temp.x>=0&&temp.x<w&&temp.y>=0&&temp.y<h){

					if(c[temp.x][temp.y]=='E'){
						return temp.step;
					}
					if(c[temp.x][temp.y]=='-'){
						vis[temp.x][temp.y]=1;
						que.push(temp);

					}
				}
			}
		}
	}
	return 0;
}




int main(void){
	
	int i,j,k;
	scanf("%d",&t);
	for(i=0;i<t;++i){
		mini=0;
		scanf("%d %d\n",&h,&w);
		for(j=0;j<h;++j){
			for(k=0;k<w;++k){
				scanf("%c",&c[k][j]);
				vis[k][j]=0;
			}
			getchar();
		}

		for(j=0;j<h;++j){
			for(k=0;k<w;++k){
				if(c[k][j]=='S'){
					a.x=k,a.y=j,a.step=0;
					mini=BFS(a);
					if(mini!=0){
						printf("%d\n",mini);
					}else{
						printf("-1\n");
					}
					break;
				}
			}
			if(k!=w)
				break;
		}
	}
	return 0;
}


 

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值