迷宫(二) 计蒜客--1596

题目链接
题目如下:

蒜头君在你的帮助下终于逃出了迷宫,但是蒜头君并没有沉浸于喜悦之中,而是很快的又陷入了思考,从这个迷宫逃出的最少步数是多少呢?

输入格式

第一行输入两个整数 n和 m,表示这是一个 n×m 的迷宫。
接下来的输入一个 n行 m列的迷宫。其中 ‘S’ 表示蒜头君的位置,’*‘表示墙,蒜头君无法通过,’.‘表示路,蒜头君可以通过’.'移动,'T’表示迷宫的出口(蒜头君每次只能移动到四个与他相邻的位置——上,下,左,右)。

输出格式

输出整数,表示蒜头君逃出迷宫的最少步数,如果蒜头君无法逃出迷宫输出 −1。
数据范围
1≤n,m≤10。

Sample Input

3 4
S**.
…*.
***T

Sample Output

-1

Sample Input 2

3 4
S**.

***T

Sample Output 2

5

这是一道搜索题,可以用深度优先搜索解答也可以用广度优先搜索解答。很标准的搜索题。题目要求得到最少步数,我们就更新到达目的地的所需步数,走过的位置需要标记。

代码如下:

#include<iostream>
using namespace std;
struct muban
{
    
    
 	int x;
 	int y;
 	int step;
}stu[8000];
char imap[15][15];
int book[15][15];
int next[4][2]={
    
    {
    
    0,1},{
    
    1,0},{
    
    0,-1},{
    
    -1,0}};
int main()
{
    
    
 	int n,m;
 	cin>>n>>m;
 	int stax,stay,endx,endy;
 	for(int i=0;i<n;i++)
 	{
    
    
  		for(int j=0;j<m;j++)
  		{
    
    
   			cin>>imap[i][j];
   			if(imap[i][j]=='S')
   			{
    
    
    				stax=i;
    				stay=j;
   			}
   			if(imap[i][j]=='T')
   			{
    
    
    				endx=i;
    				endy=j;
    				imap[i][j]='.';
   			}
  		}
 	}
 	int head,tail;
 	int tx,ty;
 	head=1;
 	stu[head].x=stax;
 	stu[head].y=stay;
 	stu[head].step=0;
 	book[stax][stay]=1;
 	tail=2;
 	int stepmin=200;
 	while(head<tail)
 	{
    
    
  		for(int i=0;i<4;i++)
  		{
    
    
   			tx=stu[head].x+next[i][0];
   			ty=stu[head].y+next[i][1];
   			if(tx>=0&&tx<n&&ty>=0&&ty<m)
   			{
    
    
    				if(book[tx][ty]==0&&imap[tx][ty]=='.')
    				{
    
    
     					stu[tail].x=tx;
     					stu[tail].y=ty;
     					stu[tail].step=stu[head].step+1;
     					book[tx][ty]=1;
     					tail++;
    				}
   			}
   			if(stu[tail-1].x==endx&&stu[tail-1].y==endy)
   			{
    
    
    				if(stu[tail-1].step<stepmin)
    				{
    
    
     					stepmin=stu[tail-1].step;
    				}
   			}
  		}
  		head++;
 	}
 	if(stepmin==200)
 	cout<<"-1\n"<<endl;
 	else
 	cout<<stepmin; 
 	return 0;
} 

猜你喜欢

转载自blog.csdn.net/Huo6666/article/details/107190386
今日推荐