HDU1180:Link Hrer
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
struct Point
{
int x,y,step;
friend bool operator < (const Point a,const Point b)
{
return a.step > b.step;
}
};
int dir[5][3] = {{1,0},{0,1},{-1,0},{0,-1}};
int n,m,s,e;
char map[22][22];
void Manage()
{
for(int i = 0;i <= n+1; i++)
{
map[i][0] = '*';
map[i][m+1] = '*';
}
for(int j = 0;j <= m+1; j++)
{
map[0][j] = '*';
map[n+1][j] = '*';
}
}
bool IsNeedPlus(Point temp,int i)
{
if(map[temp.x][temp.y] == '-'){
if(i % 2 == 0){
if(temp.step % 2 == 0)
return false;
else
return true;
}else
{
if(temp.step % 2 == 0)
return true;
else
return false;
}
}else
{
if(i % 2 == 0){
if(temp.step % 2 == 0)
return true;
else
return false;
}else
{
if(temp.step % 2 == 0)
return false;
else
return true;
}
}
}
void BFS(int u,int v)
{
priority_queue <Point>Q;
Point temp,q;
q.x= u; q.y = v; q.step = 0;
Q.push(q);
while(!Q.empty())
{
q = Q.top(); Q.pop();
if(q.x == s&&q.y == e)
{
printf("%d\n",q.step);
return ;
}
q.step ++;
for(int i = 0;i < 4;i++)
{
temp.x = q.x + dir[i][0];
temp.y = q.y + dir[i][1];
temp.step = q.step;
if(temp.x != '*')
{
if(map[temp.x][temp.y] == '.'||map[temp.x][temp.y] == 'T')
{
map[temp.x][temp.y] = '*';
Q.push(temp);
}else if(map[temp.x][temp.y]=='|'||map[temp.x][temp.y]=='-')
{
if(!IsNeedPlus(temp,i)){
temp.x += dir[i][0];
temp.y += dir[i][1];
if(map[temp.x][temp.y] != '*')
{
map[temp.x][temp.y] = '*';
Q.push(temp);
}
}else
{
Q.push(q);
}
}
}
}
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
for(int i = 1;i <= n;i++)
scanf("%s",map[i]+1);
Manage();
int u,v;
for(int i = 1;i <= n; i++)
for(int j = 1;j <= m; j++)
{
if(map[i][j] == 'S')
{
u = i;
v = j;
}
if(map[i][j] == 'T')
{
s = i;
e = j;
}
}
BFS(u,v);
}
return 0;
}