Blue Bridge: Maze

 

Maze

Time limit: 1Sec memory limit: 32MB submission: 31 Solution: 5

Title Description

Xiao Ming being in a maze, would you please help Bob find the shortest distance from the origin to the destination.
Xiaoming only moved in the four directions.

Entry

Test input comprising a plurality of sets of data. The first line of the input is an integer T, represents a group T-test data.
The first input line of each of two integers N and M (1 <= N, M <= 100).
Next N lines of M input characters, each character is represented by a small square maze.
Meaning of characters as follows:
'S': starting point
'E': end
'-': open space, by
'#': dyslexic, through
guarantee and only a start and end point of input data.

Export

For input and output from the beginning to the end of each set of minimum distance, if the path from the origin to the destination does not exist, the output of -1.

Sample input

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

Sample Output

9

 

#include<iostream>
#include<queue>
using namespace std;
struct Node {
	   int x,y;
	   int cnt;
};
char map[109][109];
int  m,n;
int  dir[4][2] = { {0,1} ,{ 0,-1 }  ,{ 1,0 } ,{ -1,0 } } ;
void bfs(int x,int y){
	 int f=0;
	 queue<struct Node> q;
	 struct Node s;
	 s.x=x;
	 s.y=y;
	 s.cnt=0;
	 q.push(s);
	 while(!q.empty()){
	 	 s = q.front();
		 q.pop();
	     for( int i=0;i<=3;i++){
		 	  int xx = s.x + dir[i][0];
		      int yy = s.y + dir[i][1];
		      if( xx >=0 && xx < m && yy >=0 && yy < n ){
		      	  if( map[xx][yy] == '-' ){
	  	       	      map[xx][yy]  = '#';
				      struct Node tmp;
				      tmp.x  = xx;
				      tmp.y  = yy;
				      tmp.cnt= s.cnt+1;
				      q.push(tmp);
				  }
			 	  if( map[xx][yy] == 'E'){
				      printf("%d\n",s.cnt+1);
				      f=1;
				      break;
				  } 
			  }
		}
		if( f )
		   break;
	 }
	  if(!f){
	 	printf("-1\n");
	 }  
}
int main(void){
    int T;
	scanf("%d",&T);
	while(T--){
		int x,y;
		scanf("%d%d",&m,&n);
		for( int i=0;i<m;i++){
			 scanf(" %s",map[i]);
			 for( int j=0;j<n;j++){
			 	  if( map[i][j] =='S'){
			 	  	  x=i;
			 	  	  y=j;
				   }
			 }
		}
		bfs(x,y);
	}
 	return 0;
}

 

Guess you like

Origin blog.csdn.net/S_999999/article/details/94596540