迷宫问题 输出路径!

定义一个二维数组: 

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)

题目其实也是用搜索找出走出去的路径,当时就是输出行走的路径的时候不好输出。

解题思路:记住解决任何题都需要解题思路,我们可以把每个扩展出去的点都弄一个标记,标记出他是从哪一个点扩展出来的,这样就好解决了。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int xx,yy,n;
int a[105][105];
int dir[4][2]={0,1,1,0,-1,0,0,-1};

struct node
{
    int x,y,num;
}shu[105];
void print(node ll)
{
    if(ll.num!=-1)print(shu[ll.num]);

    printf("(%d, %d)\n",ll.x,ll.y);
}
void dfs()
{
    node d1,d2,d3;
    int front=0,end=0;//front 表示从哪个点扩展出去的。end就是扩展出去点的储存在一个数组里。
    d1.x=0;
    d1.y=0;
    d1.num=-1;
    shu[end++]=d1;
    while(front<end)
    {
        d2=shu[front];
        front++;
        for(int i=0;i<4;i++)
        {
            d3.x=d2.x+dir[i][0];
            d3.y=d2.y+dir[i][1];
            if(a[d3.x][d3.y]==0&&d3.x>=0&&d3.x<5&&d3.y>=0&&d3.y<5)
            {
                d3.num=front-1;
                shu[end++]=d3;
                a[d3.x][d3.y]=3;
            }
            if(d3.x==4&&d3.y==4)
            {
                print(d3);
                return ;
            }
        }
    }
    return ;
}
int main()//不懂得话加输出,看一下是怎样运行的。
{
    node ll;
    int i,j;
    for(i=0;i<5;i++)
    {
        for(j=0;j<5;j++)
        {
            cin>>a[i][j];
        }
    }
    dfs();
    return ;}

搜索

    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/huxiansheng__/article/details/80529856
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞