给定一个字符数组M N,表示迷宫的行数和列数。输入迷宫数组"."表示路径通畅,“*”表示有障碍物。S为开始的位置,T为出口。
下面给出迷宫的出口和入口。
输入样例:
5 5
.....
.*.*.
.*S*.
.***.
...T*
2 2 4 3
一个固定的解题模板
#include <iostream>
#include <queue>
#define MAXN 100
using namespace std;
struct node{
int x;
int y;
int step;
}S,T,Node;
int X[4]={0,0,-1,1};
int Y[4]={-1,1,0,0};
char maze[MAXN][MAXN];
bool inq[MAXN][MAXN]={false};
int n,m;
bool test(int x,int y)
{
if(x<0||x>=m||y<0||y>=n||maze[x][y]=='*'||inq[x][y]==true)
return false;
return true;
}
int bfs()
{
queue<node> q;
q.push(S);
while(!q.empty())
{
node top=q.front();
q.pop();
if(top.x==T.x&&top.y==T.y)
return top.step;
for(int i=0;i<4;i++)
{
int new_x=top.x+X[i];
int new_y=top.y+Y[i];
if(test(new_x,new_y))
{
Node.x=new_x;
Node.y=new_y;
Node.step=top.step+1;
q.push(Node);
inq[new_x][new_y]=true;
}
}
}
return -1;
}
int main()
{
scanf("%d%d",&m,&n);
for(int i=0;i<m;i++)
{
getchar();
for(int j=0;j<n;j++)
{
maze[i][j]=getchar();
}
}
scanf("%d %d %d %d",&S.x,&S.y,&T.x,&T.y);
S.step=0;
printf("%d\n",bfs());
return 0;
}