题目 http://acm.hdu.edu.cn/showproblem.php?pid=1026
BFS+优先队列,需要记录路径。
#include <iostream> #include <stdio.h> #include <queue> using namespace std; const int maxn=100; const int inf=0x7fffffff; struct map { int f, x, y, prex, prey, time; char c; bool operator <(const struct map &m1) const { return m1.time<time; } }mp[maxn+10][maxn+10]; int dx[4]={0, 1, 0, -1}; int dy[4]={-1, 0, 1, 0}; int m, n; char cc[maxn+10]; int BFS() { priority_queue<map> q; mp[0][0].time=0, mp[0][0].f=1; q.push(mp[0][0]); while (!q.empty()) { struct map cur_m=q.top(); q.pop(); if (cur_m.x==n-1&&cur_m.y==m-1) return 1; for (int i=0; i<4; i++) { int newx=dx[i]+cur_m.x; int newy=dy[i]+cur_m.y; if (newx<0||newx>n-1||newy<0||newy>m-1||mp[newx][newy].f==1) continue; if (mp[newx][newy].c=='.') { mp[newx][newy].f=1, mp[newx][newy].time=mp[cur_m.x][cur_m.y].time+1; mp[newx][newy].x=newx, mp[newx][newy].y=newy; mp[newx][newy].prex=cur_m.x, mp[newx][newy].prey=cur_m.y; } else if (isdigit(mp[newx][newy].c)) { mp[newx][newy].f=1, mp[newx][newy].time=mp[cur_m.x][cur_m.y].time+(mp[newx][newy].c-'0')+1; mp[newx][newy].x=newx, mp[newx][newy].y=newy; mp[newx][newy].prex=cur_m.x, mp[newx][newy].prey=cur_m.y; } q.push(mp[newx][newy]); } } return 0; } void printTrace(int x, int y) { if (x==0&&y==0) return; int prex=mp[x][y].prex, prey=mp[x][y].prey; printTrace(prex, prey); int len1=mp[prex][prey].time, len2=mp[x][y].time; printf("%ds:(%d,%d)->(%d,%d)\n", len1+1, prex, prey, x, y); for (int i=len1+2; i<=len2; i++) printf("%ds:FIGHT AT (%d,%d)\n", i, x, y); } int main() { //freopen("in.txt", "r", stdin); while (scanf("%d %d", &n, &m)==2) { for (int i=0; i<n; i++) { scanf("%s", cc); for (int j=0; j<m; j++) { mp[i][j].c=cc[j]; if (mp[i][j].c=='X') mp[i][j].f=1; else mp[i][j].f=0; mp[i][j].time=inf, mp[i][j].x=i, mp[i][j].y=j; } } if (BFS()) { printf("It takes %d seconds to reach the target position, let me show you the way.\n", mp[n-1][m-1].time); printTrace(n-1, m-1); } else printf("God please help our poor hero.\n"); printf("FINISH\n"); } return 0; }