迷宫——广度优先搜索

一、Problem description

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.

Input

n,m represent the maze is a nxm maze.(n rows, m columnsm,0 <n,m <= 21).

Then is the maze.

e.g.

5 5

#####

#S..#

#.!.#

#.#E#

#####

 

Output

You need to give the least steps to walk from start to the end.If it doesn't exist, then output -1.

e.g.(for the example in input)

4


二、My answer

#include<iostream>
#include<queue>
using namespace std;
 
struct point { //  结构体保存地图上每个点的坐标
    int x;
    int y;
    point(int a = 0, int b = 0) {
    x = a;
    y = b;
}
void operator=(point a) {
    x = a.x;
    y = a.y;
}
};
int main() {
    int n, m;
    cin >> n >> m;
    int d[n][m]; //  用于记录地图上每个点与起始点之间的最短距离
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {  //  初始化数组,定义为-1的原因是为了方便下面判断移动点是否被标记
            d[i][j] = -1;
        }
    }
    char map[21][21];
    queue<point> q;  // 确保遍历点的顺序
    point start(0, 0);  //  起始点
    point end(0, 0);  //  终点
    int dx[4] = {1, 0, -1, 0};  //  移动方向的坐标, 地图上每个点有四种不同的移动方向
    int dy[4] = {0, 1, 0, -1};  //  也可定义为dxy[4][2] = {{1, 0},{0, 1},{-1, 0},{0, -1}}
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> map[i][j];
            if (map[i][j] == 'S') {  //  找到起始点的坐标
                start.x = i;
                start.y = j;
            } else if (map[i][j] == 'E') {
                end.x = i;  // 找到终点的坐标
                end.y = j;
            }
        }
    }
    q.push(start);  //  压入起始点
    point p;
    d[start.x][start.y] = 0; //  起始点与自己之间的距离为零
    while (!q.empty()) {
        p = q.front();
        q.pop();
        if (p.x == end.x&&p.y == end.y) {  //  结束的标志
            break;
        }
        for (int i = 0; i < 4; i++) {
            int nx = p.x + dx[i];
            int ny = p.y + dy[i];  //  每个点都遍历它所能移动的四个方向,再判断移动产生的新点是否符合条件
            if (nx >= 0&&nx < n&&ny >= 0&&ny < m&&map[nx][ny] != '#'&&map[nx][ny] != '!'
			&&d[nx][ny] == -1) {  //  判断上述产生的新点是否符合, 条件为所在位置没有障碍
                q.push(point(nx, ny));       // 点在地图范围内且最重要的是该点未被标记即d[nx][xy] = -1
                d[nx][ny] = d[p.x][p.y]+1;  // 符合的点压入队列
            }
        }
    }
    if (d[end.x][end.y] == -1) {
        cout << "-1" << endl; //  输出答案
    } else {
        cout << d[end.x][end.y] << endl;
    }
}
三、小结

利用了广度优先搜索寻找最优解即在这里为最短距离。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值