hdu1242
//bfs+优先队列 #include<cstdio> #include<cstring> #include<queue> using namespace std; const int ROW = 201; const int COL = 201; const int DIRS = 4; char map[ROW][COL]; int dir[DIRS][2] = {-1,0,0,1,1,0,0,-1}; struct priNode { int x, y, time; friend bool operator < (priNode a, priNode b) { return a.time > b.time; } }; bool inMap(int pi, int pj, int row, int col); int bfs(int ai, int aj, int row, int col, int *ans); int main(void) { int n, m; int i, j; int ai, aj; while (scanf("%d%d", &n, &m) != EOF) { for (i=0; i<n; ++i) { scanf("%s", map[i]); for (j=0; j<m; ++j) { if (map[i][j] == 'a') { //angle's position ai = i; aj = j; break; } } } int time = 0; if (bfs(ai, aj, n, m, &time)) { printf("%d\n", time); }else { printf("Poor ANGEL has to stay in the prison all his life.\n"); } } return 0; } bool inMap(int pi, int pj, int row, int col) { return (pi>=0 && pi<row && pj >=0 && pj < col); } int bfs(int ai, int aj, int row, int col, int *ans) { int i; priNode now, next; priority_queue<priNode> Q; now.x = ai; now.y = aj; now.time = 0; Q.push(now); map[ai][aj] = '#'; while (!Q.empty()) { now = Q.top(); Q.pop(); if (map[now.x][now.y] == 'r') { *ans = now.time; return 1; } for (i=0; i<DIRS; ++i) { next.x = now.x + dir[i][0]; next.y = now.y + dir[i][1]; if (inMap(next.x, next.y, row, col)) { if (map[next.x][next.y] == '.' || map[next.x][next.y]=='r') { next.time = now.time + 1; if (map[next.x][next.y] == '.') { map[next.x][next.y] = '#'; } Q.push(next); }else if (map[next.x][next.y] == 'x') { next.time = now.time + 2; map[next.x][next.y] = '#'; Q.push(next); } } } } return 0; }