#include <iostream>
#include <queue>
using namespace std;
const int N = 25;
struct node
{
int x, y, time;
};
char a[N][N];
int mark[N][N];
int x1, y11, x2, y2;
int dis[4][2] = {{1,0}, {-1, 0}, {0, 1}, {0, -1}};
void bfs()
{
queue<node> q;
node s1, s2;
s1.x = x1;
s1.y = y11;
s1.time = 0;
q.push(s1);
int i;
memset(mark, 0, sizeof(mark));
mark[s1.x][s1.y] = 1;
while(!q.empty())
{
s1 = q.front();
q.pop();
if(s1.x == x2 && s1.y == y2)
{
printf("%d\n", s1.time);
return;
}
for(i = 0; i < 4; i++)
{
s2.x = s1.x + dis[i][0];
s2.y = s1.y + dis[i][1];
if(mark[s2.x][s2.y] == 0 && a[s2.x][s2.y] != '*')
{
if(a[s2.x][s2.y] == '.')
{
s2.time = s1.time + 1;
q.push(s2);
mark[s2.x][s2.y] = 1;
}
if(a[s2.x][s2.y] == '-' && (s1.time & 1) == 0 || a[s2.x][s2.y] == '|' && s1.time & 1)
{
if(s2.x == s1.x)
{
s2.y = s2.y + s2.y - s1.y;
s2.time = s1.time + 1;
if(a[s2.x][s2.y] != '*' && mark[s2.x][s2.y] == 0)
{
q.push(s2);
mark[s2.x][s2.y] = 1;
mark[s1.x][s1.y] = 1;
}
}
else
{
s2.x = s2.x + s2.x - s1.x;
s2.time = s1.time + 1;
q.push(s2);
}
}
if(a[s2.x][s2.y] == '|' && (s1.time & 1) == 0 || a[s2.x][s2.y] == '-' && s1.time & 1)
{
if(s2.y == s1.y)
{
s2.x = s2.x + s2.x - s1.x;
s2.time = s1.time + 1;
if(a[s2.x][s2.y] != '*' && mark[s2.x][s2.y] == 0)
{
q.push(s2);
mark[s2.x][s2.y] = 1;
mark[s1.x][s1.y] = 1;
}
}
else
{
s2.y = s2.y + s2.y - s1.y;
s2.time = s1.time + 2;
q.push(s2);
}
}
}
}
}
}
int main()
{
int n, m, i, j;
while(cin >> n >>m)
{
memset(a, '*', sizeof(a));
for(i = 1; i <= n; i++)
{
for(j = 1; j <= m; j++)
{
cin >> a[i][j];
if(a[i][j] == 'S')
{
x1 = i;
y11 = j;
}
else if(a[i][j] == 'T')
{
x2 = i;
y2 = j;
a[i][j] = '.';
}
}
getchar();
}
bfs();
}
return 0;
}
HDU 1180 诡异楼梯 bfs
最新推荐文章于 2019-09-04 19:15:06 发布