解救人质 DFS简单模板

解救人质,给一张二维地图,有障碍的点不能移动,给定起始点和人质坐标,求到达人质路程的最短路程,DFS模型
#include <iostream>
#include <cstdio>

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 next_x,next_y,k;

    //判断是否到达小哈的位置
    if(x==p&&y==q){
        //更新最小值
        if(step<Min)
            Min=step;
        return ;
    }
    for(k=0;k<=3;k++){
        next_x=x+next[k][0];
        next_y=y+next[k][1];
        //判断是否越界
        if(next_x<1||next_x>n||next_y<1||next_y>m)
            continue;
        //判断改点是否为障碍物或者已经在路径中
        if(a[next_x][next_y]==0&&book[next_x][next_y]==0)
        {
            book[next_x][next_y]=1;//标记已走过
            dfs(next_x,next_y,step+1);//开始尝试下一个点
            book[next_x][next_y]=0;//想象下,在地图上,到头后开始回溯,取消标记
        }
    }
    return ;
}
int main()
{
    int i,j,start_x,start_y;
    cin>>n>>m;
    for(i=1;i<=n;i++)
        for(j=1;j<=m;j++)
        cin>>a[i][j];
    cin>>start_x>>start_y>>p>>q;

    //从起点开始搜索
    book[start_x][start_y]=1;
    dfs(start_x,start_y,0);

    cout<<Min;
    return 0;
}


原文地址:https://www.cnblogs.com/mingrigongchang/p/6246267.html