您的位置:首页 > 其它

hdu 1180 优先队列 + bfs

2013-08-06 15:50 507 查看
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1180

1 //优先队列 + bfs
2 //wrong1 楼梯是每分钟变化一次 wrong2 奇偶性判断错误
3 #include <iostream>
4 #include <cstring>
5 #include <queue>
6 #include <cstdio>
7 using namespace std;
8 int n, m, sx, sy, dir[4][2] = {{1,0}, {-1,0}, {0,-1}, {0,1}};
9 char map[25][25]; bool visit[25][25];

bool OK(int x, int y){
if(x > 0 && y > 0 && x <= n && y <= m && !visit[x][y] && map[x][y] != '*') return true;
return false;
}

struct node{
int x, y, step;
bool operator < (const node& n) const{
return step > n.step;
}
};

void bfs(){
priority_queue<node> q; node n1, n2, n3;
n1.x = sx; n1.y = sy; n1.step = 0; q.push(n1);
while(!q.empty()){
n1 = q.top(); q.pop();
if(map[n1.x][n1.y] == 'T'){ cout<<n1.step<<endl; break;}
for(int i = 0; i < 4; ++i){
n2.x = n1.x + dir[i][0]; n2.y = n1.y + dir[i][1]; n2.step = n1.step + 1;
if(!OK(n2.x, n2.y)) continue;
if(map[n2.x][n2.y] == '|' || map[n2.x][n2.y] == '-'){
n3.x = n2.x + dir[i][0]; n3.y = n2.y + dir[i][1]; n3.step = n2.step;
if(!OK(n3.x, n3.y)) continue;//根据奇偶性判断是否需要等到下一分才能过楼梯
if((map[n2.x][n2.y] == '|' && (n1.step & 1) && i < 2) ||
(map[n2.x][n2.y] == '|' && !(n1.step & 1) && i > 1) ||
(map[n2.x][n2.y] == '-' && !(n1.step & 1) && i < 2) ||
(map[n2.x][n2.y] == '-' && (n1.step & 1) && i > 1))
n3.step++;
visit[n3.x][n3.y] = true;
q.push(n3); continue;
}
visit[n2.x][n2.y] = true; q.push(n2);
}
}
}

int main()
{
//freopen("in.txt", "r", stdin);
while(cin>>n>>m){
for(int i = 1; i <= n; ++i){
cin>>(map[i]+1);
for(int j = 1; j <= m; ++j)
if(map[i][j] == 'S') sx = i, sy = j;
}
memset(visit, false, sizeof(visit));
visit[sx][sy] = true;
bfs();
}
return 0;
}

View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: