您的位置:首页 > 其它

HDU 2822 Dogs【两次bfs】

2015-03-24 21:17 260 查看
6 6

..X...

XXX.X.

....X.

X.....

X.....

X.X...

3 5 6 3

如上一个图 告诉起点和终点 X到达不费力气 .到达花费1 问从起点到终点 最少的花费力气

分析:bfs 遇到X在bfs

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;

const int maxn = 1005;
char s[maxn][maxn];
int vis[maxn][maxn];
int n, m;
int x0, y0, xn, yn;

struct Node {
int x, y, id;
bool operator<(const Node &n0) const{
return id > n0.id;
}
};
priority_queue<Node> q, qq;

int xx[4] = { 0, 0, 1, -1 };
int yy[4] = { 1, -1, 0, 0 };

bool bfs2(Node n0) {
while(!qq.empty()) {
qq.pop();
}
qq.push(n0);
Node n2;
while(!qq.empty()) {
Node n1 = qq.top(); qq.pop();
if(n1.x == xn && n1.y == yn) return true;
for(int i = 0; i < 4; i++) {
int tx = n1.x + xx[i];
int ty = n1.y + yy[i];
if(tx >= 0 && tx < n && ty >= 0 && ty < m && !vis[tx][ty] && s[tx][ty] == 'X') {
vis[tx][ty] = vis[n1.x][n1.y];
n2.x = tx; n2.y = ty; n2.id = vis[tx][ty];
qq.push(n2);
q.push(n2);
}
}
}
return false;
}

void bfs() {
while(!q.empty()) q.pop();
memset(vis, 0, sizeof(vis));
vis[x0][y0] = 1;
Node n0 = (Node) {x0, y0, vis[x0][y0]};
q.push(n0);
if(s[x0][y0] == 'X') {
if(bfs2(n0)) return;
}
Node n2;
while(!q.empty()) {
Node n1 = q.top();q.pop();
if(n1.x == xn && n1.y == yn) return ;
for(int i = 0; i < 4; i++) {
int tx = n1.x + xx[i];
int ty = n1.y + yy[i];
if(tx >= 0 && tx < n && ty >= 0 && ty < m && !vis[tx][ty]) {
if(s[tx][ty] == 'X') {
vis[tx][ty] = vis[n1.x][n1.y];
n2.x = tx; n2.y = ty; n2.id = vis[tx][ty];
if(bfs2(n2)) return ;
q.push(n2);
} else {
vis[tx][ty] = vis[n1.x][n1.y] + 1;
n2.x = tx; n2.y = ty; n2.id = vis[tx][ty];
q.push(n2);
}
}
}
}
}

int main() {
while(scanf("%d %d",&n, &m) ) {
if(n == 0 && m == 0) break;
for(int i = 0; i < n; i++) {
scanf("%s",s[i]);
}
scanf("%d %d %d %d",&x0, &y0, &xn, &yn);
x0--; y0--; xn--; yn--;
bfs();
printf("%d\n", vis[xn][yn] - 1);
}
return 0;
}


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