主要就是输出路径问题;
pre[x][y]表示到达(x,y)是由点(pre[x][y].x, pre[x][y].y)而来;
#include<stdio.h> #include<iostream> #include<string.h> #include<queue> #include<algorithm> using namespace std; #define N 220 #define INF 0xfffffff int dir[4][2] = { {1,0},{-1,0},{0,1},{0,-1} }; int map[N][N]; int vis[N][N], n, m; struct node { int x, y, step; friend bool operator<(node a, node b) { return a.step>b.step; } }pre[N][N],path[N]; node bfs() { memset(vis, 0,sizeof(vis)); vis[0][0] = 1; priority_queue<node> Q; node p,q; p.x = p.y = p.step = 0; Q.push(p); while(Q.size()) { p=Q.top(); Q.pop(); if(p.x == 4 && p.y == 4) return p; for(int i=0; i<4; i++) { q.x=p.x+dir[i][0]; q.y=p.y+dir[i][1]; if(q.x>=0&&q.x<5 && q.y>=0&&q.y<5 && map[q.x][q.y]==0 && vis[q.x][q.y]==0) { vis[q.x][q.y] = 1; q.step = p.step + 1; pre[q.x][q.y].x = p.x; pre[q.x][q.y].y = p.y; Q.push(q); } } } } int main() { for(int i=0; i<5; i++) { for(int j=0; j<5; j++) scanf("%d",&map[i][j]); } node ans = bfs(); int step = ans.step, x = ans.x, y = ans.y; for(int i=step-1; i>=0; i--) { path[i].x = pre[x][y].x; path[i].y = pre[x][y].y; x = path[i].x; y = path[i].y; } for(int i=0;i<step;i++) { printf("(%d, %d) ",path[i].x, path[i].y); } printf("(4, 4) "); return 0; }