zoukankan      html  css  js  c++  java
  • 迷宫问题 (bfs广度优先搜索记录路径)

    • 问题描述:

    定义一个二维数组: 

    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,用pre记录上一个位置,最后用回溯的方法输出路径。
    • 代码:

    #include<cstdio>
    #include<queue>
    #include<cstring>
    #include<iostream>
    using namespace std;
    int b[6][6];
    int a[6][6];
    int next[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
    struct node
    {
        int x,y;
        int pre;
    }que[510];
    int tx,ty;
    
    void print(int s)
    {
        if(que[s].pre!=-1)
        {
            print(que[s].pre);
            printf("(%d, %d)
    ",que[s].x,que[s].y);
        }
    }
    
    void bfs(int x,int y)
    {
        int head=1,tail=1;
        que[tail].x=x;
        que[tail].y=y;
        que[tail].pre=-1;
        tail++;
        while(head<tail)
        {
            for(int i=0;i<4;i++)
            {
                tx=que[head].x+next[i][0];
                ty=que[head].y+next[i][1];
                if(tx<0||tx>=5||ty<0||ty>=5)continue;
                if(b[tx][ty]==0&&a[tx][ty]==0)
                {
                    b[tx][ty]=1;
                    que[tail].x=tx;
                    que[tail].y=ty;
                    que[tail].pre=head;
                    tail++;
                }
                if(tx==4&&ty==4)
                    print(head);
            }
            head++;
        }
    }
    
    int main()
    {
        for(int i=0;i<5;i++)
        {
            for(int j=0;j<5;j++)
            {
                scanf("%d",&a[i][j]);
            }
        }
        memset(b,0,sizeof(b));
        b[0][0]=1;
        printf("(0, 0)
    ");
        bfs(0,0);
        printf("(4, 4)
    ");
        return 0;
    }
  • 相关阅读:
    317 随笔
    316 随笔
    315 随笔
    python 第一章
    matlab 第四章 第一节 字符串 元胞
    matlab 第三章 第二节 多维数组
    matlab 第三章
    python 循环+break continue
    Springboot 教程 导入
    matlab 第二章 第三节 数值表示、变量及表达式
  • 原文地址:https://www.cnblogs.com/boboyuzz/p/10493127.html
Copyright © 2011-2022 走看看