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

来源:互联网 发布:java static 编辑:程序博客网 时间:2024/05/17 08:15


 

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

15 5S-###-----##---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;}


 

 

0 0