Maze is a very interesting game, can exercise people's memory and thinking. Now, HK is trapped in a maze, please help him find a shortest path, can let him out of the maze.
The maze uses a n*m matrix to describe the matrix with '. ' Represent the space can pass, use ' * ' stands for obstacles, use ' S ' to represent the starting point, use ' T ' to represent the exit. For example, a matrix below describes a 8*8 maze.
..... T..
.. *****.
......*.
*.***.*.
......*.
.****.*.
S.. *....
........
Each character represents 1 squares, and HK can only move between the grid and the upper and lower directions.
Input
Each input file contains only one set of input data.
The first row of each group of data is two positive integers N and M (n,m<=100).
Then there is a matrix of n*m.
Output
If HK can get out of the maze, output the minimum number of steps required; otherwise output-1.
This problem is a relatively simple wide-search problem:
A layer of the diagram, rather than a deep search, suddenly go to the bottom of the graph;
#include <iostream>#include<queue>#include<cstring>using namespacestd;Chara[ the][ the];intvis[ -][ -];intax[5]={-1,0,1,0};intay[5]={0,-1,0,1};intn,m;structthing{intx, y; intStep;} End, Start,now;intBFs () {Queue<Thing>que; Que.push (start); while(!Que.empty ()) { Now=Que.front (); if(now.x = = End.X && Now.y = =end.y) { returnNow.step; } que.pop (); for(inti =0; I <4; i++) {Thing temp; Temp.x= now.x+Ax[i]; TEMP.Y= Now.y +Ay[i]; Temp.step= now.step+1; if(Temp.x >=0&& temp.x < n && temp.y >=0&& temp.y < M && a[temp.x][temp.y]!='*'&&!VIS[TEMP.X][TEMP.Y]) {Que.push (temp); VIS[TEMP.X][TEMP.Y]=1; } } } return-1;}intMain () { while(Cin >> N >>m) {memset (A,0,sizeof(a)); memset (Vis,0,sizeof(VIS)); for(inti =0; i < n; i++) {cin>>A[i]; } for(inti =0; I < n; i++){ for(intj =0; J < M; J + +){ if(A[i][j] = ='S') {Start.x=i; Start.y=J; Start.step=0; VIS[I][J]=1; } if(A[i][j] = ='T') {end.x=i; End.y=J; } }} cout<< BFS () <<Endl; }}
View Code
A. Walk the Maze 1