ACM 之 J - 迷宫问题

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)

理解:

0表示可以走的路径,找到最短的路径然后把路径坐标挨个输出.搜索最佳路径问题,尤其是最短路径问题都可以用广度搜索来解决.
所以不知道的同学又要去学习啦~BFS

代码部分

#include<iostream>
#include<stack>
using namespace std;
int i,j,ff,num,front,a[5][5],b[5][5],c[5][5];
stack<int>x;
stack<int>y;
void dfs(int i,int j)//这里函数名命名错了,但是不影响程序运行。。。
{
    if(a[i][j]==1||i<0||j<0||i>=5||j>=5||b[i][j]==1) return ;
    if(c[i][j]==0&&a[i][j]==0&&b[i][j]==0)
    {
        c[i][j]=ff;
        b[i][j]=1;
        ff++;
    }
    dfs(i,j+1);
    dfs(i+1,j);
    dfs(i-1,j);
    dfs(i,j-1);
}
int main()
{
    for(i=0;i<5;i++)
        for(j=0;j<5;j++)
        {
            cin>>a[i][j];
            b[i][j]=0;
            c[i][j]=0;
        }
    ff=1;
    for(i=0;i<5;i++)
    {
        for(j=0;j<5;j++)
        {
            if(a[i][j]==0)
            {dfs(i,j);}
        }
    }
    front = c[4][4];
    int fu=front;
    for(num=fu-1;num>0;num--)
    {
        for(i=4;i>=0;i--)
        {
            for(j=4;j>=0;j--)
            {
                if(c[i][j]==front-1&&c[i][j]!=0)
                {
                    x.push(i);
                    y.push(j);
                    front=c[i][j];
                }
            }
        }
    }
    while(!x.empty()&&!y.empty())
    {
        cout<<"("<<x.top()<<", "<<y.top()<<")\n";
        x.pop();y.pop();
    }
    cout<<"("<<4<<", "<<4<<")\n";
    return 0;
}

意见反馈 || 任何建议

联系我(新浪)
邮箱:qianlizhihao@gmail.com

    原文作者:Gadore千里
    原文地址: https://www.jianshu.com/p/7b74d97dbc8f
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞