zoukankan      html  css  js  c++  java
  • DFS迷宫问题模型(具体模拟过程见《啊哈算法》)

    问题描述:小哈在n×m的矩形迷宫里迷了路,小哼来解救小哈。已知小哈在迷宫的坐标为(p, q),小哼最开始站在在迷宫的第0行第0列。问小哼最少要走多少步才能走到小哈的所在位置。

    输入:n,m(n行m列的迷宫),

              n行m列的迷宫

              p,q(小哈所在位置的横坐标,小哈所在位置的纵坐标)

    输出:小哼最少要走的步数

    代码:

    #include<stdio.h>
    #include<algorithm>
    #include<iostream>
    #include<string.h>
    #include<math.h>
    #include<set>
    #include<map>
    using namespace std;
    int n,m,min1=999999;
    int book[51][51],a[51][51];
    int p,q;
    void dfs(int x,int y,int step)
    {
        int i;
        int dir[10][10]={{0,1},{1,0},{0,-1},{-1,0}};
        if(x==p&&y==q)  //判断是否到达小哈的位置
        {
            if(step<min1)
                min1=step;
            return ;
        }
        else
        {
            int tx,ty;
            for(i=0;i<4;i++)
            {
                tx=x+dir[i][0];
                ty=y+dir[i][1];  //计算下一个点的坐标
                if(tx<1||tx>n||ty<1||ty>m)
                {
                    continue;
                }  //判断是否越界
                else
                {
                    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()
    {
            scanf("%d%d",&n,&m);
            int i,j;
            for(i=1;i<=n;i++)
            {
                for(j=1;j<=m;j++)
                {
                    scanf("%d",&a[i][j]);
                }
            }
            scanf("%d%d",&p,&q);
            book[0][0]=1;  //标记起点已在路径中,防止后面重复走
            dfs(1,1,0);
            printf("%d",min1);
        return 0;
    }

  • 相关阅读:
    RedissonConfProperty
    IdGenerator(雪花)
    Btrace和arthas地址
    SqlFilter
    AuthorityFilter
    111
    分布式数据库-杂记
    站点集群
    分布式精华文章
    高并发
  • 原文地址:https://www.cnblogs.com/programming123/p/10827532.html
Copyright © 2011-2022 走看看