給定一個n*m的二維整數陣列,用來表示一個迷宮,陣列中只包含0或1,其中0表示可以走的路,1表示不可通過的墻壁,
最初,有一個人位于左上角(1, 1)處,已知該人每次可以向上、下、左、右任意一個方向移動一個位置,
請問,該人從左上角移動至右下角(n, m)處,至少需要移動多少次,
資料保證(1, 1)處和(n, m)處的數字為0,且一定至少存在一條通路,
輸入格式
第一行包含兩個整數n和m,
接下來n行,每行包含m個整數(0或1),表示完整的二維陣列迷宮,
輸出格式
輸出一個整數,表示從左上角移動至右下角的最少移動次數,
資料范圍
1≤n,m≤1001≤n,m≤100
輸入樣例:
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
輸出樣例:
8
將每個位置點的狀態都用一個佇列存盤起來,第一次往外深搜一步,第二次深搜兩步,第三次深搜三步,依次疊加直到無法搜索為止,
#include <iostream> #include <cstring> #include <algorithm> #include <queue> using namespace std; typedef pair<int, int> PII; const int N = 110; int n, m; int g[N][N], d[N][N]; int bfs(){ queue<PII> q; memset(d, -1, sizeof d); d[0][0] = 0; q.push({0,0}); int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; while(q.size()){ auto t = q.front(); q.pop(); for(int i = 0; i < 4; i++){ int x = t.first + dx[i], y = t.second + dy[i]; if(x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1){ d[x][y] = d[t.first][t.second] + 1; q.push({x,y}); } } } return d[n - 1][m - 1]; } int main() { cin >> n >> m; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) cin >> g[i][j]; cout << bfs() << endl; return 0; }View Code
待修改補充
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/145119.html
標籤:其他
上一篇:Fast and slow pointers for cycle detection in linked list
