迷宫问题 BFS

迷宫(BFS)

标签: 算法


题目描述

You are provided a maze(迷宫), and you need to program to find the least steps to walk from the start to the end.And you can only walk in four directions:up, down,left, right.
There will only be 5 kinds of characters in the maze.The meaning of each is as followed.
“#” is for rock, which you can not walk through.
“S” is for start.
“E” is for end.
“.” is for road.
“!” is for magma(岩浆),which you can not walk through.
e.g.

#####
#S..#
#.!.#
#.#E#
#####

算法实现

首先将出发点压入队列,从此节点开始探索,由它产生的可能四个方向,如果走得通,就将其压入队列。每次从队列拿出一个节点,循环上次步骤直至队列为空或者到达终点。

代码实现

#include <iostream>
#include <queue>

using namespace std;

char maze[100][100];
int dir[4][2] = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}}; //用数组来代替位移w, s, a, d

struct Node {
    int x, y;
    int step; //步数记录
    Node(int x_, int y_, int step_): x(x_), y(y_), step(step_) {}
};

int SearchTheWay(int s_x, int s_y, 
                   int e_x, int e_y,
                   int m_m, int m_n) {
  Node node(s_x, s_y, 0);
  queue<Node> q;
  q.push(node);
  while (!q.empty()) {
    node = q.front();
    q.pop();
    if (node.x == e_x && node.y == e_y) //如果该点为终点
        return node.step;
    maze[node.y][node.x] = '#';
    for (int i = 0; i < 4; i++) {
        int x = node.x + dir[i][0];   //通过循环来遍历wsad四个方向
        int y = node.y + dir[i][1];
        if (x >= 0 && y >= 0 && x <= m_m && y <= m_n &&
              (maze[y][x] == '.' || maze[y][x] == 'E')) {
          maze[y][x] = '#'; //将走过的路换成墙,防止回溯
          Node temp(x, y, node.step + 1); //注意step+1这一细节
          q.push(temp);
        }
    } 
  }
  return -1; //如果无路,则返回-1
}

int main() {
    int m, n;
    int start_x, start_y;
    int end_x, end_y;
    cin >> m >> n;
    for (int i = 0; i < m; i++) 
        cin >> maze[i];
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (maze[i][j] == 'S') {
                start_x = j;
              start_y = i;
            }
            if (maze[i][j] == 'E') {
                end_x = j;
                end_y = i;
            }
        }
    }
    int result = SearchTheWay(start_x, start_y, end_x, end_y, n, m);
    cout << result << endl;
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值