poj3984

题目名称:迷宫问题

题目链接:http://poj.org/problem?id=3984


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)


思路:dfs+路径记录,题目已经固定走的起点和终点和行列数


代码如下:

 

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
int a[6][6],sum;
int vis[26];
int fa[26],cnt;
int dir[9]={-1,0,1,0,0,-1,0,1};
queue<int> q;
void bfs()
{
    vis[0]=1;
    while(!q.empty())
        q.pop();
    q.push(0);
    while(!q.empty())
    {
        int d=q.front();
        q.pop();
        for(int i=0;i<=3;i++)
        {
            int x=d%5;  //用一维的写成二维的
            int y=d/5;
            int newx=x+dir[i*2];
            int newy=y+dir[i*2+1];
            cnt=newx+newy*5;
            if(newx<0||newx>=5||newy<0||newy>=5) continue;
            if(vis[cnt]) continue;
            if(a[newx][newy]==1) continue;
            vis[cnt]=vis[d]+1;
            if(fa[cnt]==-1)  //记录该点的上一个点
            {
                fa[cnt]=d;
            }
            q.push(cnt);
            if(cnt==24)
                break;
        }
    }
}
int main()
{
    for(int i=0;i<5;i++)
        for(int j=0;j<5;j++)
        {
            scanf("%d",&a[i][j]);
        }
    memset(fa,-1,sizeof(fa));
    memset(vis,0,sizeof(vis));
    sum=0;
    bfs();
    stack<int> m;
    int i=24;
    while(fa[i]!=-1)
    {
        m.push(i);    //因为记录的是反过来的,所以要反过来输出
        i=fa[i];
    }
    printf("(0, 0)\n");
    while(!m.empty())
    {
        int a=m.top();
        m.pop();
        printf("(%d, %d)\n",a%5,a/5);
    }
    return 0;
}

 

 

 

posted @ 2015-07-16 20:17  maplefighting  阅读(118)  评论(0编辑  收藏  举报