深度优先搜索DFS(迷宫问题)

问题及代码:

给出迷宫的图纸和初始终点位置,用DFS求最小步数。

#include <iostream>
using namespace std;
int n,m,p,q,MIN=99999999;
int a[51][51],book[51][51];

void dfs(int x,int y,int step)
{
    int next[4][2]= {{0,1},{1,0},{0,-1},{-1,0}}; //顺时针:右下左上
    int tx,ty,k;
    if(x==p&&y==q)//是否到达
    {
        if(step<MIN)
            MIN=step;
        return;
    }
    //枚举四种方向的走法
    for(k=0; k<4; ++k)
    {
        tx=x+next[k][0];//计算坐标
        ty=y+next[k][1];
        if(tx<1||tx>n||ty<1||ty>m)//越界
            continue;
        if(a[tx][ty]==0&&book[tx][ty]==0)
        {
            book[tx][ty]=1;//标记走过
            dfs(tx,ty,step+1);
            book[tx][ty]=0;//尝试结束后取消标记
        }
    }
    return ;
}

int main()
{
    int i,j,sx,sy;
    cin>>n>>m;//行、列
    for(i=1; i<=n; ++i)
        for(j=1; j<=m; ++j)
            cin>>a[i][j];//迷宫图
    cin>>sx>>sy>>p>>q;//迷宫入口和目标坐标
    book[sx][sx]=1;//从起点开始搜索,且起点已经在路程中
    dfs(sx,sy,0);//0表示初始步数
    cout<<MIN<<endl;
    return 0;
}
/*测试用例
5 4
0 0 1 0
0 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
1 1 4 3
*/

运行结果:

《深度优先搜索DFS(迷宫问题)》

阿,就是再回过头熟悉一下DFS算法:从一个方向走,走不通再回去尝试另外一个方向。

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