【每天一道算法題】走迷宮


輸入描述:

輸入包含多組數據。

每組數據包含一個10*10,由“#”和“.”組成的迷宮。其中“#”代表牆;“.”代表通路。

入口在第一行第二列;出口在最后一行第九列。

從任意一個“.”點都能一步走到上下左右四個方向的“.”點。



輸出描述:

對應每組數據,輸出從入口到出口最短需要幾步。

 

輸入例子:

#.########
#........#
#........#
#........#
#........#
#........#
#........#
#........#
#........#
########.#


#.########
#........#
########.#
#........#
#.########
#........#
########.#
#........#
#.######.#
########.#

走迷宮,不應該說是一道題,應該說是一類題。之前華為OJ上也有。不過它只要求計算能不能走出迷宮,並沒有要求最少步數。

其實就是構建一棵樹。出口節點所在的層數就是其最少的步數,而start節點就是根節點。在這棵樹上執行BFS算法。

自定義一個struct存儲坐標位置,及該節點,所在層數。

BFS:

1、根節點入隊列(這里是start入隊)

2、讀取其周圍位置,類似其孩子節點。

3、判斷是否到達出口節點,走到其孩子節點,將其標志為visited。

 

如果最后沒有到達出口節點且隊列已空,說明無法找到路徑至出口,返回0。

#include <vector>
#include <iostream>
#include <queue>
using namespace std;
 
struct pos {
    int x;
    int y;
    int level;
};
int BFS(vector<vector<char>>& map) {
    const int dir[4][2] = { {1,0},{-1,0},{0,1},{0,-1} };
    queue<pos> q;
    int m = map.size();
    int n = map[0].size();
 
    vector<vector<bool>> visited(m, vector<bool>(n, false));
    pos start = { 0,1,0 }, end = { 9,8,0 };
    q.push(start);
    visited[start.x][start.y] = true;
    while (!q.empty()) {
        pos tmp = q.front(), nextpos;
        q.pop();
         
        for (int i = 0; i < 4; i++) {
            nextpos.x = tmp.x + dir[i][0];
            nextpos.y = tmp.y + dir[i][1];
            nextpos.level = tmp.level + 1;
            if (nextpos.x == end.x&&nextpos.y == end.y)
                return nextpos.level;
 
                if (nextpos.x >= 0 && nextpos.x < m&&nextpos.y >= 0 && nextpos.y < n&&visited[nextpos.x][nextpos.y] == false&&map[nextpos.x][nextpos.y]=='.') {
                    q.push(nextpos);
                    visited[nextpos.x][nextpos.y] = true;
                }
        }
    }
 
        return 0;
}
 
int main() {
    vector<vector<char>> map(10, vector<char>(10));
 
    while (cin >> map[0][0]) {
        for (int i = 0; i < 10; i++)
            for (int j = 0; j < 10; j++)
            {
                if (i == 0 && j == 0) continue;
                cin >> map[i][j];
            }
        cout << BFS(map) << endl;
    }
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM