• 迷宫问题


    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)
    题解
    用数组记录已经走过的点,并且标记已经走过的路,但注意当所选的那条不能到达时 要向上找点,此时便要把之前已经记录的点去掉;
    #include <iostream>
    #include<algorithm>
    #include<cstdio>
    #include<cmath>
    #include<cstring>
    #include<cstdlib>
    #include<stack>
    #include<queue>
    using namespace std;
    int a[5][5];//记录迷宫
    int point[25],point1[25];//记录走过的点
    int dx[4]={1,0,-1,0};
    int dy[4]={0,1,0,-1};
    int i,j,ans;
    void dfs(int n,int m)//输入 初始位置
    {
        for(int k=0;k<4;k++)
        {
            int nx = n + dx[k];//利用数组进行坐标变化
            int ny = m + dy[k];
            if(nx >= 0&&nx < 5&&ny >= 0&&ny < 5&&a[nx][ny]==0)//保证在迷宫内,且检测是否可行
            {
                a[nx][ny]=1;//标记走过的点
                point[ans] = nx;//记录经过的点的坐标
                point1[ans] = ny;
                ans+=1;
                if(nx==4&&ny==4)//到达终点
                {
                    for(int k=0;k< ans ;k++)
                    {
                        printf("(%d, %d)
    ",point[k],point1[k]);
                    }
                    break;
                }
                else
                    dfs(nx,ny);
                    a[nx][ny]=0;//当所选的路径不能到达终点,返回上一次的位置
                    point[ans] = nx;//去掉之前的记录的点
                    point1[ans] = ny;
                    ans--;
            }
        }
    }
    int main()
    {
        for(i=0;i<5;i++)
        {
            for(j=0;j<5;j++)
            {
                scanf("%d",&a[i][j]);
            }
        }
        printf("(0, 0)
    ");
        dfs(0,0);
        return 0;
    }
    
  • 相关阅读:
    hdu 5119 Happy Matt Friends
    hdu 5128 The E-pang Palace
    hdu 5131 Song Jiang's rank list
    hdu 5135 Little Zu Chongzhi's Triangles
    hdu 5137 How Many Maos Does the Guanxi Worth
    hdu 5122 K.Bro Sorting
    Human Gene Functions
    Palindrome(最长公共子序列)
    A Simple problem
    Alignment ( 最长上升(下降)子序列 )
  • 原文地址:https://www.cnblogs.com/Staceyacm/p/10782135.html
Copyright © 2020-2023  润新知