迷宮,較為高效的C++代碼 BFS實現

來源:互聯網
上載者:User

同樣的BFS,這種方法相對記憶體佔用較小。

複製別人的代碼,學習了!

題目描述:

sun所在學校每年都要舉行電腦節,今年電腦節有一個新的趣味比賽項目叫做闖迷宮。
sun的室友在幫電腦節設計迷宮,所以室友就請sun幫忙計算下走出迷宮的最少步數。
知道了最少步數就可以輔助控制比賽難度以及去掉一些沒有路徑到達終點的map。
比賽規則是:從原點(0,0)開始走到終點(n-1,n-1),只能上下左右4個方向走,只能在給定的矩陣裡走。

輸入:

輸入有多組資料。
每組資料輸入n(0<n<=100),然後輸入n*n的01矩陣,0代表該格子沒有障礙,為1表示有障礙物。
注意:如果輸入中的原點和終點為1則這個迷宮是不可達的。

輸出:

對每組輸入輸出該迷宮的最短步數,若不能到達則輸出-1。

範例輸入:
20 10 050 0 0 0 01 0 1 0 10 0 0 0 00 1 1 1 01 0 1 0 0
範例輸出:
28
#include<stdio.h>
#include<queue>
#define INF 0x7fffffff
using namespace std;
struct S {
int x, y;
S(int i, int j) {
x = i, y = j;
}
};
int M[102][102], D[102][102], n, i, j, t;
int main() {
while (~scanf("%d", &n)) {
for (i = 0; i < n; ++i)
for (j = 0; j < n; ++j)
D[i][j] = INF,scanf("%d", &M[i][j]);
queue<S> r;
--n;
if (M[0][0] || M[n][n]) {
puts("-1");
continue;
}
r.push(S(0, 0));
D[0][0] = 0;
while (!r.empty()) {
i = r.front().x, j = r.front().y;
r.pop();
t = D[i][j] + 1;
if (i - 1 >= 0 && !M[i - 1][j] && D[i - 1][j] > t)
D[i - 1][j] = t, r.push(S(i - 1, j));
if (j - 1 >= 0 && !M[i][j - 1] && D[i][j - 1] > t)
D[i][j - 1] = t, r.push(S(i, j - 1));
if (i + 1 <= n && !M[i + 1][j] && D[i + 1][j] > t)
D[i + 1][j] = t, r.push(S(i + 1, j));
if (j + 1 <= n && !M[i][j + 1] && D[i][j + 1] > t)
D[i][j + 1] = t, r.push(S(i, j + 1));
}
if (D[n][n] >= INF)
D[n][n] = -1;
printf("%d\n", D[n][n]);
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.