从迷宫开始的s点走到t点,其中*代表墙壁,.代表平地。
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <vector>
#include <map>
#include <queue>
using namespace std;
const int maxn = 100;
struct Node{
int x,y;
int step;
};
Node start,end,temp;
int n,m;
char maze[maxn][maxn];
bool flag[maxn][maxn];
int mx[4]={0,0,1,-1};
int my[4]={1,-1,0,0};
bool Is_push(int x,int y)
{
if(x>=n||x<0||y>=m||y<0) return false;
if(flag[x][y] == true) return false;
if(maze[x][y] == '*') return false;
return true;
}
void bfs()
{
int i;
queue<Node>q;
q.push(start);
flag[start.x][start.y] = true;
while(!q.empty())
{
temp = q.front();
if(temp.x == end.x&&temp.y == end.y)
return;
int layer = temp.step;
q.pop();
for(i=0;i<4;i++)
{
int newx = temp.x+mx[i];
int newy = temp.y+my[i];
if(Is_push(newx,newy))
{
Node n;
n.x = newx;
n.y = newy;
n.step = layer+1;
q.push(n);
flag[newx][newy] = true;
}
}
}
}
int main()
{
cin>>n>>m;
int i,j;
for(i = 0;i < n;i++)
{
getchar();
for(j = 0;j < m; j++)
{
maze[i][j] = getchar();
}
}
cin>>start.x>>start.y>>end.x>>end.y;
start.step = 0;
bfs();
cout<<temp.step<<endl;
}
测试案例:
5 5
…
...
.S.
.**.
…T
输出:11