bfs队列的算法,走迷宫

problem description

有一个二维迷宫,n行m列,‘s’表示迷宫的起点,‘T’表示迷宫的终点,‘#’表示围墙,‘.’表示通路。

现在从S出发,你不能穿墙,问到达终点T最少需要多少步?

输入格式

第一行输入n,m(1<=n,m<=50)表示迷宫的行列大小。

接下来输入n行字符串表示迷宫。

输出格式

一个整数,表示走出迷宫所需的最小步数,若走不出迷宫则输出 -1。

样例输入1

2 3
S.#
..T

样例输出1

3

样例输入2

3 3
S.#
.#.
.#T

样例输出2

-1
# include <cstdio>
# include <stdio.h>
# include <iostream>
# include <queue>
using namespace std;
const int maxn=1000;
typedef struct node {
	int x;
	int y;
	int f;
	node (int a,int b,int c)//这里面参数要是不同的
	{x=a;y=b;f=c;}//将坐标看做结构体在队列中操作 
}node;
queue<node>q;//q里面放的是结构体 
int m,n;
char map[maxn][maxn];
int vis[maxn][maxn];
int s[2][2];
int val;
char ch;
int dp[4][2]={1,0,-1,0,0,1,0,-1};
int bfs(int x,int y,int f)
{
  	q.push(node(x,y,f));
  	vis[x][y]=1;
    while (!q.empty())//这里去(!q.empty())
  	     {	  
		 node p=q.front();
		 q.pop();
  	     if (p.x==s[1][0]&&p.y==s[1][1]) 
  	        return p.f;
  	     for (int i=0;i<4;++i)
  	        {
  	          int x=p.x+dp[i][0];
			  int y=p.y+dp[i][1];
			  if (x<0||y<0||x>m-1||y>n-1||vis[x][y]==1||map[x][y]=='#') continue;
			  q.push(node(x,y,p.f+1));//这里是p.f+1,你要考虑到这个深度相同的 
			  vis[x][y]=1;	
			}
		 }
	return -1;
}
int main ()
{
    cin>>m>>n;
    ch=getchar();
    for (int i=0;i<m;++i)
       {
       	for (int j=0;j<n;++j)
       	   {
       	   	 cin>>map[i][j];
       	   	 if (map[i][j]=='S') {s[0][0]=i;s[0][1]=j;}
       	   	 if (map[i][j]=='T') {s[1][0]=i;s[1][1]=j;}
		   }
       	ch=getchar();
	   }
	int t=bfs(s[0][0],s[0][1],0);
	printf ("%d\n",t);
	return 0;
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值