给你一个 n 行 m 列的二维迷宫。'S'表示起点,'T' 表示终点,'#' 表示墙壁,'.' 表示平地。你需要从 'S' 出发走到 'T',每次只能上下左右走动,并且不能走出地图的范围以及不能走到墙壁上。请你计算出走到终点需要走的最少步数。输入格式第一行输入 nnn, mmm 表示迷宫大小。(1≤n,m≤100)(1 \leq n,m \leq 100)接下来输入 nnn 行字符串表示迷宫,每个字符串长度为 mm。(地图保证有且仅有一个终点,一个起始点)输出格式输出走到终点的最少步数,如果不能走到终点输出 -1−1,占一行。
样例输入1
2 3
S.#
..T
样例输出1
3
样例输入2
3 3
S.#
.#.
.#T
样例输出2
-1
wa:bfs第一次上手,还差一步,无法区分每一条路的步数
#include<iostream>
#include<queue>
using namespace std;
char map[200][200];
bool vis[200][200];
int sx,sy,ex,ey;
int n,m;
void intial()
{
int n,m,i,j;
n=m=200;
for(i=0;i<=n+1;++i)
{
for(j=0;j<=m+1;++j)
{
map[i][j]='#';
vis[i][j]=false;
}
}
}
struct point
{
int x,y;
point(int xx,int yy)
{
x=xx;
y=yy;
}
};
int print(int x,int y)
{
for(int i=1;i<=x;++i)
{
for(int j=1;j<=y;++j)
{
cout<<map[i][j];
}
cout<<endl;
}
}
int bfs(int x,int y,int bs)
{
int flag=0;
queue <point> q;
q.push(point(x,y));
map[x][y]='#';
struct point temp(0,0);
while(!q.empty())
{
temp = q.front();
q.pop();
int xx[4]={0,0,1,-1};
int yy[4]={1,-1,0,0};
int tx,ty;
for(int i=0;i<4;++i)
{
tx= temp.x+xx[i];
ty= temp.y+yy[i];
// print(n,m);
if(map[tx][ty]!='#'&&map[tx][ty]!='T')
{
map[tx][ty]='#';
bs++;
//cout<<bs<<" "<<tx<<","<<ty<<endl;
q.push(point(tx,ty));
//cout<<q.size()<<"empty = "<<q.empty()<<endl;
//cout<<"hello"<<endl;
}
else if(map[tx][ty]=='T')
{
flag=1;
//bs++;
//print(n,m);
//cout<<q.size()<<endl;
// cout<<bs<<" "<<tx<<","<<ty<<" "<<map[tx][ty]<<endl;
goto stop;
}
}
}
stop:if(flag)
{
return bs;
}
else
{
return -1;
}
}
int main()
{
int i,j;
intial();
cin>>n>>m;
for(i=1;i<=n;++i)
{
for(j=1;j<=m;++j)
{
cin>>map[i][j];
if(map[i][j]=='S')
{
sx=i;
sy=j;
}
if(map[i][j]=='T')
{
ex=i;
ey=j;
}
}
}
cout<<bfs(sx,sy,0);
return 0;
}
ac代码解析:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
int a[105][105],mark[105][105],b[105][105];
int mn=0;
int chx[4]={1,0,-1,0};
int chy[4]={0,1,0,-1};
struct point
{
int x;
int y;
point(int xx,int yy)
{
x=xx;
y=yy;
}
};
int bfs(int i,int j)
{
queue<point>q;
q.push(point(i,j));
mark[i][j]=1;
while(!q.empty())
{
i=q.front().x;
j=q.front().y;
q.pop();
for(int k=0;k<4;k++)
{
int tx=i+chx[k];
int ty=j+chy[k];
//这个点可以走>0 并且之前没走到
if(!mark[tx][ty]&&a[tx][ty])
{
mn=b[i][j]+1;
b[tx][ty]=mn;
//用于统计步数:mn=当前的步数=上一次的步数+1
cout<<i<<","<<j<<"="<<b[i][j];
cout<<";"<<tx<<","<<ty<<"="<<b[tx][ty]<<endl;
mark[tx][ty]=1;
//标记一下已经走过的点
if(a[tx][ty]==2)return 1;
else q.push(point(tx,ty));
//把派生子路入栈
}
}
}
return 0;
}
int main()
{
int n,m;int bx,by;
char ip1;
cin>>n>>m;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
cin>>ip1;
if(ip1=='S')
{
//记录初始点
bx=i;by=j;
}
else if(ip1=='.')a[i][j]=1;//可走为1
else if(ip1=='T')a[i][j]=2;//终点为2
else a[i][j]=0;//不可走为0
}
if(bfs(bx,by))printf("%d\n",mn);
else printf("-1\n");
return 0;
}