ACWING 844.迷路を歩く

アドレス:https : //www.acwing.com/problem/content/846/

  左上隅から右下隅まで迷路を歩き、0は行くことができる、1は行くことができない、少なくともいくつかのステップを尋ねます。

  BFSソリューション:g [] []を介してマップを記録し、d [] []を-1に初期化して、ポイントが1度だけ移動できるようにし、各ポイントから終点までの距離を記録します。

  注:キューの記録(x、y)を実装するには、次のステートメントを使用します。

#include <queue> 
typedef pair < intint > pp; 
キュー < int > q; 
q.push({ 12 })。
pp t = q.front; 
那么:t.first = 1、t.second = 2
#include <iostream> 
#include <cstdio> 
#include <cstring> 
#include <queue>
 using  namespace std; 
typedef pair < intint > P; // !!! 
const  int maxn = 105 ;
 int n、m;
 int G [MAXN] [MAXN];
 INT D [MAXN] [MAXN];     // 各点距離まで開始から// 移動しない
int型 DX [] {= 00、 - 11 };
 int型のDy [ ] = { 1、-100 }。
int bfs()
{ 
    キュー <P> q; 
    memsetの(D、 - 1はsizeof (d)参照)。
    d [ 0 ] [ 0 ] = 0 ; 
    q.push({ 00 })。
    while(!q.empty())
    { 
        P t = q.front(); 
        q.pop(); 
        forint 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;
    forint i = 0 ; i <n; i ++forint j = 0 ; j <m; j ++ 
            cin >> g [i] [j]; 
    cout << bfs()<< endl;
    0を返し ます
}

 

おすすめ

転載: www.cnblogs.com/liyexin/p/12680832.html