zoj 1649 Rescue【bfs】
题目连接: http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=649
大致题意:求r到a最少用多长时间,走到‘.'的时间为1,走到‘x'的时间为2,’#‘不能走。
代码:
#include<stdio.h>
#include<string.h>
#include<limits.h>
#include<algorithm>
#include<queue>
using namespace std;
#define M 201
char map[M][M]; //存放地图。
int counts[M][M]; //存放从r到每个点的最小时间。
int n, m;
int dir[4][2] =
{
{1, 0}, {0, 1}, {-1, 0}, {0, -1}
};
//该点横纵坐标。
struct node {
int x, y;
};
void bfs(node post)
{
queue<node> Q;
Q.push(post);
while( !Q.empty() ) {
node tmp;
tmp.x = Q.front().x;
tmp.y = Q.front().y;
Q.pop();
for(int i = 0; i < 4; i++) {
node next;
next.x = tmp.x + dir[i][0];
next.y = tmp.y + dir[i][1];
if(next.x >= 0 && next.x < n && next.y >= 0 && next.y < m && map[next.x][next.y] != '#') {
if(map[ next.x ][ next.y ] == '.' && counts[next.x][next.y] > counts[tmp.x][tmp.y]+1) {
counts[next.x][next.y] = counts[tmp.x][tmp.y]+1;
Q.push( next );
} else if(map[ next.x ][ next.y ] == 'x' && counts[next.x][next.y] > counts[tmp.x][tmp.y]+2) {
counts[next.x][next.y] = counts[tmp.x][tmp.y]+2;
Q.push( next );
} else if(map[ next.x ][ next.y ] == 'a') {
counts[next.x][next.y] = min(counts[next.x][next.y], counts[tmp.x][tmp.y]+1);
}
}
}
}
}
int main()
{
while(scanf("%d %d%*c", &n, &m) != EOF) {
//初始化最大。
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
counts[i][j] = INT_MAX;
}
}
node post; //r点的坐标。
int ai, aj; //目标点的坐标。
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
scanf("%c", &map[i][j]);
if(map[i][j] == 'r') {
post.x = i;
post.y = j;
}
if(map[i][j] == 'a') {
ai = i;
aj = j;
}
}
scanf("%*c");
}
counts[post.x][post.y] = 0;
bfs(post);
if(counts[ai][aj] == INT_MAX) {
printf("Poor ANGEL has to stay in the prison all his life.\n");
} else {
printf("%d\n", counts[ai][aj]);
}
}
return 0;
}

浙公网安备 33010602011771号