POJ 3984(bfs加路径)

来源:互联网 发布:中石油国际事业部 知乎 编辑:程序博客网 时间:2024/05/21 15:45
/*bfs题目,先用这个搜索到出口,在搜索的过程,记录上一个结点,找到终点,就可以来 依次找口起点,这样,就可以输出路径; */#include<iostream> #include<cstring>#include<stack>#include<queue>using namespace std;typedef struct point {int x,y;} point;const int dx[4] = {-1, 1, 0 , 0};  const int dy[4] = {0 , 0, -1, 1};queue<point> que;int map[5][5];point flag[6][6];void bfs(point tp){point p1;que.push(tp);while(que.size()){tp = que.front();que.pop();if(tp.x == 4 && tp.y == 4){return ;}for(int i=0; i<4; ++i){int nx = tp.x + dx[i];int ny = tp.y + dy[i];if(nx>=0 && ny>=0 && nx<=4 && ny<=4 && map[nx][ny] != 1 && flag[nx+1][ny+1].x == 0 && flag[nx+1][ny+1].y == 0){p1.x = nx, p1.y = ny;que.push(p1);if(nx == 0 && ny ==0) continue;flag[nx+1][ny+1].x = tp.x+1;flag[nx+1][ny+1].y = tp.y+1;}}}}void printResult(){stack<point> res;point tp;int x,y,nx = 5,ny = 5;while(nx!=-1 && ny!=-1){tp.x = nx-1, tp.y = ny-1;res.push(tp);x = nx, y = ny;nx = flag[x][y].x;ny = flag[x][y].y;}while(!res.empty()){tp = res.top();res.pop();printf("(%d, %d)\n", tp.x, tp.y);}}int main(){for(int i=0; i<5; ++i){for(int j=0; j<5; ++j){cin>>map[i][j];}}point p1;p1.x = 0, p1.y = 0;bfs(p1);flag[1][1].x = -1;flag[1][1].y = -1;printResult();return 0;}

原创粉丝点击