您的位置:首页 > 其它

HDU 1180 BFS+优先队列 +!!一个致命的低级错误!!

2013-07-24 20:50 429 查看
真的是一个致命的弱智错误;

注释后带change:的是原来的代码;

我想着,最后迟早time要+1的,提前+1 和后来+1 应该一样。可是 问题就处在这儿。后面 还有对time的奇偶性的判断, 如果事先加了1就会改变奇偶性了;

真的是低级错误; 花了我一天时间了。

错误出现了也是好事,起码我解决了这个错误;

希望以后不会再犯了;在此谢谢张晨阳,一语道破;

ok。。。continue;

/*
*Author   ID:fuqiang11
*Problem  ID:HDU 1180
*Submit Time:2013/7/24
*Algorithm  :BFS
*/
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
#define maxn 22

struct point
{
int x;
int y;
int time;
friend bool operator < (point a, point b)
{
return a.time > b.time;
}
};

int n,m;
char map[maxn][maxn];
bool visit[maxn][maxn];
int xx[] = {0,0,1,-1};
int yy[] = {1,-1,0,0};

bool check(int x, int y) // 检查下一步是否能继续 越界,碰墙则不能继续
{
if(x<1||y<1||x>n||y>m||map[x][y]=='*'||visit[x][y])
return false;
return true;
}

int after(point b, int i)  //过楼梯后时间的计算
{
if(b.time % 2 == 0)  //过楼梯前时间为偶数
{
if(map[b.x][b.y] == '-')  //与当前楼梯状态相反
{
if(i==2 || i==3) b.time++;
}
else
{
if(i==0 || i==1) b.time++;
}
}
else  //过楼梯前时间为奇数
{
if(map[b.x][b.y] == '|')  //与当前楼梯状态相同 由于时间是奇数,所以相反了
{
if(i==2 || i==3) b.time++;
}
else
{
if(i==0 || i==1) b.time++;
}
}
return b.time+1;//change: return b.time;
}
void BFS(point st, point ed)
{
priority_queue <point> q;
q.push(st);
point a,b;
while(!q.empty())
{
a = q.top();
q.pop();
if(a.x==ed.x && a.y==ed.y)
{
printf("%d\n",a.time);
return ;
}
for(int i = 0; i < 4; i++)
{
b.x = a.x + xx[i];
b.y = a.y + yy[i];
b.time = a.time; //change : b.time = a.time + 1;
if(check(b.x, b.y))
{
if(map[b.x][b.y]=='.')
{
b.time++; //change : nothing
if(b.x == ed.x && b.y == ed.y)
{
printf("%d\n",b.time);
return ;
}
q.push(b);
visit[b.x][b.y] = true;
}
else
{
b.time = after(b,i);
b.x += xx[i];
b.y += yy[i];
if(check(b.x, b.y))
{
if(b.x==ed.x && b.y==ed.y)
{
printf("%d\n",b.time);
return ;
}
q.push(b);
visit[b.x][b.y] = true;
}//end if
}//end else
}//end if
}//end for
}//end while
}//end BFS

int main()
{
point st,ed;
while(scanf("%d%d",&n,&m)!=EOF)
{
getchar();
for(int i = 1; i <= n; i++)
{
gets(map[i]+1);
for(int j = 1; j <= m; j++)
{
if(map[i][j] == 'S')
{
st.x = i;
st.y = j;
}
if(map[i][j]=='T')
{
ed.x = i;
ed.y = j;
map[i][j] = '.';  //将结束节点 修改为空位
}
}
}
memset(visit,false,sizeof(visit));
visit[st.x][st.y] = true;
st.time = 0;
BFS(st,ed);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: