迷宫问题(BFS, DFS)

The Core Thoughts

核心思想

  • DFS (Depth First Search):
  • 深度优先搜索

  Save the path that can go through using Stack (if it can go through at present, push it to the Stack). When there is no way to go, then go back to the path that has not yet been searched through backtracking. If there is no result when backtracking until the Stack is empty, there is no solution.

  使用栈保存可以通过的路径(只要如果目前可以通过,则将该位置压栈)。 当无路可走时,再通过回溯回到尚未搜索到的路径。 如果回溯到栈为空时还没有结果,则无解。

  Use the queue to save all the traversable positions and expand the traversable routes in the queue layer by layer until it reaches the exit position. If the last queue is empty, there is no solution.

  使用队列保存所有的可遍历位置,将队列中的可遍历路径逐层展开,直到到达出口位置。 如果最后队列为空,则无解。

Source Code

源代码

#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
using namespace std;

struct Box {
    int x;
    int y;
    int nextDirection;
    Box(int x, int y, int nextDirection) : x(x), y(y), nextDirection(nextDirection) {};
};

struct Box_1 {
    int x;
    int y;
    Box_1* prior; // The pointer to the prior point
    Box_1(int x, int y, Box_1* prior) : x(x), y(y), prior(prior) {};
};

vector<vector<int>> GenerateMaze() {
    int row, col;
    cout << "The number of rows and columns:" << endl;
    cin >> row >> col;

    cout << "Input the maze:" << endl;
    // The maze should be expanded by 2 lengths to comprise the frame of the maze
    vector<vector<int>> Maze(row + 2, vector<int>(col + 2, 1));
    for (int i = 1; i < row + 1; i++) {
        for (int j = 1; j < col + 1; j++) {
            cin >> Maze[i][j];
        }
    }
    return Maze;
}

bool IsValidPosition(int x, int
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值