您的位置:首页 > 编程语言 > C语言/C++

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

2013-12-16 00:33 1316 查看
 

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;
}


 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息