アドレス:https : //www.acwing.com/problem/content/846/
左上隅から右下隅まで迷路を歩き、0は行くことができる、1は行くことができない、少なくともいくつかのステップを尋ねます。
BFSソリューション:g [] []を介してマップを記録し、d [] []を-1に初期化して、ポイントが1度だけ移動できるようにし、各ポイントから終点までの距離を記録します。
注:キューの記録(x、y)を実装するには、次のステートメントを使用します。
#include <queue> typedef pair < int、int > pp; キュー < int > q; q.push({ 1、2 })。 pp t = q.front; 那么:t.first = 1、t.second = 2
#include <iostream> #include <cstdio> #include <cstring> #include <queue> using namespace std; typedef pair < int、int > P; // !!! const int maxn = 105 ; int n、m; int G [MAXN] [MAXN]; INT D [MAXN] [MAXN]; // 各点距離まで開始から// 移動しない int型 DX [] {= 0、0、 - 1、1 }; int型のDy [ ] = { 1、-1、0、0 }。 int bfs() { キュー <P> q; memsetの(D、 - 1、はsizeof (d)参照)。 d [ 0 ] [ 0 ] = 0 ; q.push({ 0、0 })。 while(!q.empty()) { P t = q.front(); q.pop(); for(int i = 0 ; i < 4 ; i ++ ) { int x = dx [i] +t.first; int y = dy [i] + t.second; if(x> = 0 && y> = 0 && x <n && 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; 0を返し ます。 }