poj3984 迷宫问题(bfs+路径)

来源:互联网 发布:阿里云 ecs 挂载云盘 编辑:程序博客网 时间:2024/05/08 02:57


http://poj.org/problem?id=3984

题意:给你个5x5矩阵,输出左上角到右下角的路径。


思路:用栈记录,细心。


#include <stdio.h>#include <algorithm>#include <stdlib.h>#include <string.h>#include <iostream>#include <queue>#include <stack>using namespace std;typedef long long LL;const int N = 10;const int INF = 0x3f3f3f3f;int G[N][N];bool vis[N][N];int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};struct node{    int x, y, step, prex, prey;    friend bool operator < (const node &a, const node &b)    {        return a.step > b.step;    }};node path[N][N];bool check(int x, int y){    if(x>=0 && x<=4 && y>=0 && y<=4 && !vis[x][y] && G[x][y]!=1) return true;    else return false;}void bfs(int x, int y){    memset(vis, false, sizeof(vis));    priority_queue<node>que;    node s;    s.x = x;    s.y = y;    s.step = 0;    vis[x][y] = true;    que.push(s);    while(!que.empty())    {        node tmp = que.top();        que.pop();        if(tmp.x==4 && tmp.y==4)        {            path[tmp.x][tmp.y] = tmp;            break;        }//注意终止顺序        for(int i = 0; i < 4; i++)        {            node tmp2;            tmp2 = tmp;            tmp2.x += dir[i][0];            tmp2.y += dir[i][1];            if(check(tmp2.x, tmp2.y))            {                vis[tmp2.x][tmp2.y] = true;                tmp2.prex = tmp.x;                tmp2.prey = tmp.y;                que.push(tmp2);//进队列顺序前要把前驱处理好                path[tmp2.x][tmp2.y] = tmp2;            }        }    }}void Print(){    stack<node>sta;    node now = path[4][4];    sta.push(now);    while(1)    {        now = path[now.prex][now.prey];        sta.push(now);        if(now.x==0 && now.y==0) break;    }    while(!sta.empty())    {        now = sta.top();        sta.pop();        printf("(%d, %d)\n", now.x, now.y);    }}int main(){ //   freopen("in.txt", "r", stdin);    for(int i = 0; i < 5; i++)        for(int j = 0; j < 5; j++)        {            cin >> G[i][j];        }    bfs(0, 0);    Print();    return 0;}


0 0