Java教程

迷宫问题(bfs基础)

本文主要是介绍迷宫问题(bfs基础),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一,正常的迷宫问题

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 <cstring>
#include <algorithm>
#include <queue>
using namespace std;
//首先是地图
int map[6][6];
int book[6][6];
int dir[4][2] = { {-1,0},{1,0},{0,-1},{0,1} };
//这个是方向数组我为啥一直不会写
struct node {
    //一个结点
    int x, y;//两个坐标
    int c;//这个是父节点
}Queue[6 * 6];



//我整个程序写完之后再看一下这个递归的意义
void  Print(int head) {
    //这个print函数是用来返回路径的
    while (Queue[head].c != -1) {
        Print(Queue[head].c);
        cout << Queue[head].x << Queue[head].y;
        return;
    }
    cout << "(0,0)" << endl;
}

void bfs(int x, int y) {
    //先初始化一下队列
    int head = 0, tail = 1;
    int i;
    Queue[0].x = 0;
    Queue[0].y = 0;
    Queue[0].c = -1;
    struct node now;
    while (head < tail) {
        //这个路径打印过程到底是怎么回事
        if (Queue[head].x == 4 && Queue[head].y == 4){
            //这个其实就是判头,和上面的其实是一样的
            Print(head);
            return;
        }
        //后面就开始走的过程了
        for (i = 0; i < 4; i++) {
            now.x = Queue[head].x + dir[i][0];
            now.y = Queue[head].y + dir[i][1];
            now.c = head;
            if (now.x >= 0 && now.x <= 4 && now.y >= 0 && now.y <= 5) {
                if (!book[now.x][now.y] && !map[now.x][now.y]) {
                    book[now.x][now.y] = 1;
                    Queue[tail] = now;
                    tail++;
                }
            }
        }
        head++;
        //这个head其实就是头元素
    }
}
int main() {
    int i, j;
    for (i = 0; i < 5; i++) {
        for (j = 0; j < 5; j++) {
            cin >> map[i][j];
        }
    }
    memset(book, 0, sizeof(book));
    bfs(0,0);
    return 0;
}

 

 

 

 

这篇关于迷宫问题(bfs基础)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!