hihocoder 1519 : 逃离迷宫II

本文介绍了一种利用广度优先搜索(BFS)算法解决迷宫问题的方法,特别关注于寻找从起点到终点最少转弯次数的路径。通过详细的代码实现说明了如何在遇到墙壁或边界时进行转弯计数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://hihocoder.com/problemset/problem/1519?sid=1167472

要求拐弯最小次数,并且只有碰到墙或者碰到地图边界才能拐弯。
bfs,每次入队的点是当前点往各方向一条道走到黑时候的点。
注意这种情况:
5 5
S#…
…..
..T..
…..
…..

判断到没到终点要每走一步就判断,否则会误判上面的情况。

#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <unordered_map>
#include <algorithm>
#include <stdio.h>
#include <string.h>

using namespace std;

char board[505][505];
int n, m;
int r, c;
int dx[4] = { 0, 0, 1, -1 };
int dy[4] = { 1, -1, 0, 0 };
bool visited[505][505][4];

struct point {
    int x, y, s;
    int d;
    point() {}
    point(int _x, int _y, int _s, int _d) : x(_x), y(_y), s(_s), d(_d) {}
};

bool valid(int x, int y) {
    if (x < 0 || x >= n || y < 0 || y >= m || board[x][y] == '#') {
        return false;
    }
    return true;
}

int bfs(int x, int y) {
    queue<point> Q;
    for (int i = 0; i < 4; ++i) {
        int next_x = x, next_y = y;
        while (valid(next_x + dx[i], next_y + dy[i])) {
            next_x += dx[i];
            next_y += dy[i];
            if (board[next_x][next_y] == 'T') {
                return 0;
            }
        }
        visited[next_x][next_y][i] = true;
        Q.push(point(next_x, next_y, 0, i));
    }
    while (!Q.empty()) {
        point cur = Q.front();
        Q.pop();
        //cout << " x " << cur.x << " y " << cur.y << " d " << cur.d << endl;
        if (board[cur.x][cur.y] == 'T') {
            return cur.s;
        }
        for (int i = 0; i < 4; ++i) {
            int next_x = cur.x, next_y = cur.y;
            while (valid(next_x + dx[i], next_y + dy[i])) {
                next_x += dx[i];
                next_y += dy[i];
                if (board[next_x][next_y] == 'T') {
                    return cur.s + 1;
                }
            }
            if (!visited[next_x][next_y][i]) {
                visited[next_x][next_y][i] = true;
                Q.push(point(next_x, next_y, cur.s + 1, i));
            }
        }
    }
    return -1;
}

int main() {
    while (cin >> n >> m) {
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                cin >> board[i][j];
                if (board[i][j] == 'S') {
                    r = i;
                    c = j;
                }
            }
        }
        memset(visited, false, sizeof(visited));
        int ans = bfs(r, c);
        cout << ans << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值