http://ybt.ssoier.cn:8088/problem_show.php?pid=1252
《走迷宫》BFS模板
#include<bits/stdc++.h>
#define UP(i,x,y) for(int i=x; i<=y; i++)
#define N 200
using namespace std;
struct Node{
int a=0;
int b=0;
int step=0;
};
int R,C;
char myMap[N][N];
int dir[5][5];
int book[N][N]={0};
Node myQueue[N*N];
int head=0,tail=1;
/*
从a,b出发走到 ea,eb的最短步数
*/
int bfs(int a, int b, int ea, int eb)
{
/* 初始化队列第一个元素为(a, b) */
int ta, tb;
myQueue[head].a = a;
myQueue[head].b = b;
myQueue[head].step = 1;
book[a][b] = 1;
while(head < tail)
{
/* 扩展出新的四个点 */
UP(i, 1, 4)
{
ta = myQueue[head].a + dir[i][1];
tb = myQueue[head].b + dir[i][2];
/* ---- 不能入队的情况 ---- */
/* 越界 */
if(ta>R || ta<=0 || tb>C || tb<=0)
{
continue;
}
/* 找到终点 */
if(ta == R and tb == C)
{
return myQueue[head].step + 1;
}
/* ---- 可以入队的情况 ---- */
if(book[ta][tb] == 0 and myMap[ta][tb] == '.')
{
myQueue[tail].a = ta;
myQueue[tail].b = tb;
myQueue[tail].step = myQueue[head].step+1;
book[ta][tb]=1; //标记下 不能走了
tail++;
}
}
head++;
}
return 0;
}
int main()
{
dir[1][1] = -1;
dir[2][1] = 1;
dir[3][2] = -1;
dir[4][2] = 1;
/* 读入数据 */
cin>>R>>C;
UP(i, 1, R)
{
UP(j, 1, C)
{
cin>>myMap[i][j];
}
}
cout<<bfs(1,1, 5,5);
return 0;
}