poj 3984 迷宫问题

迷宫问题
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 4323   Accepted: 2476

Description

定义一个二维数组:

int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

Input

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

Output

左上角到右下角的最短路径,格式如样例所示。

Sample Input

0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

第一次写BFS算法,还是折腾了一下的。。。。
#include<iostream>
#include<queue>
#include<stack>
using namespace std;

struct node
{
    int x;
    int y;
};

queue<node> q;
stack<node> s;

int map[5][5];
node p[5][5];

int movex[] = {-1, 1, 0, 0};
int movey[] = {0, 0, 1, -1};

int judge(int a, int b)
{
    if(a>=5 || b>=5 || a<0 || b<0 || map[a][b]==1)
        return 0;
    return 1;
}

int main()
{
    //freopen("e:\\data.txt", "r", stdin);   
    //freopen("e:\\out.txt", "w", stdout); 
    int i, j;
    for(i = 0; i < 5; ++i)
    {
        for(j = 0; j < 5; ++j)
        {
            cin>>map[i][j];
        }
    }
    node n;
    n.x = 0;
    n.y = 0;
    map[0][0] = 1;
    q.push(n);
    int a, b;
    while(!q.empty())
    {
        node temp = q.front();
        q.pop();
        for(i = 0; i < 4; ++i)
        {
            a = temp.x + movex[i];
            b = temp.y + movey[i];
            if(judge(a, b))
            {
                map[a][b] = 1;
                node next;
                next.x = a;
                next.y = b;
                p[a][b].x = temp.x;
                p[a][b].y = temp.y;
                q.push(next);
            }
        }
    }

    node end;
    end.x = 4;
    end.y = 4;
    s.push(end);
    node parent = s.top();
    
    while(parent.x!=0 || parent.y!=0)
    {    
        parent = p[parent.x][parent.y];
        s.push(parent);
    }
    while(!s.empty())
    {
        node t = s.top();
        cout<<"("<<t.x<<", "<<t.y<<")"<<endl;
        s.pop();
    }
}
        

 

posted @ 2012-05-07 14:45  w0w0  阅读(204)  评论(0)    收藏  举报