zoukankan      html  css  js  c++  java
  • 2016HUAS暑假集训题1 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)

    分析:
    本题为一迷宫,从左上方走到右下方经过的最短路线,典型的bfs问题 先到达就退出 主要是打印路线 可以用一个值来保存经过的最短路线然后倒向追踪打印路线
    Ac代码:
    #include <iostream>
    #include<cstring>
    using namespace std;
    int top = -1,under = 0,visit[100][2],dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}},queue[100],a[5][5],v,s[100];
    void queue_push(int x)
    {
        queue[++top] = x;
    }
    int queue_pop()
    {
        return queue[under++];
    }
    int main()
    {
        int i,j;
        for(i = 0; i < 5; i++)
        {
          for(j = 0; j < 5; j++)
          {
            cin>>a[i][j];
          }
        }
        memset(visit,0,sizeof(visit));
        queue_push(0);
        visit[0][0] = 1;
        while(under<=top)
        {
                v = queue_pop();
                if(v == 24) break;
                int x = v/5,y = v%5;
                for(int i = 0;i < 4;i++)
                {
                    int px = x+dir[i][0],py = y +dir[i][1];
                   if(visit[px*5+py][0] == 0&&a[px][py] == 0&&px>=0&&px<5&&py>=0&&py<5)
                   {
                       queue_push(px*5+py);  //满足条件添加进数组
                       visit[px*5+py][0] = 1;   //标记已经经过此点
                       visit[px*5+py][1] = v;  //保存路线
                   }
                }
        }
    
        for( i = 1,s[0] = 24;s[i-1] != 0; i++ )
        {
            s[i] = visit[s[i-1]][1];
        }
        for(  j = i- 1;j >= 0; j--)
        {
            cout<<"("<<s[j]/5<<", "<<s[j]%5<<")"<<endl;
        }
        return 0;
    }



  • 相关阅读:
    angular反向代理配置
    实现对Asp.NetMvc及Asp.NetCore的权限控制
    C# 语言特性发展史
    在angular 6中使用 less
    使用WeihanLi.Redis操作Redis
    [svc]jq神器使用
    [sh]shell脚本栗子
    [k8s]nginx-ingress配置4/7层测试
    [svc]nginx-module-vts第三方模块安装配置
    [k8s]helm原理&私有库搭建&monocularui和kubeapp探究
  • 原文地址:https://www.cnblogs.com/LIUWEI123/p/5676858.html
Copyright © 2011-2022 走看看