[Acwing#24]ロボットの移動範囲(BFS-DFS)

トピック出典:https://www.acwing.com/problem/content/22/

接地グリッドとm行n列、水平および垂直座標の範囲、それぞれ0〜M-1および0〜N-1。

グリッドからロボットが移動グリッドを移動させるだけ左たびに、右、上、下四方、0,0を調整します。

しかし、グリッドの行および列の座標へのアクセスがkビットの数の合計よりも大きいです。

ロボットは、格子の数に到達することができるだろうか?

サンプル1

入力:K = 7、M = 4、N = 5

出力:20

サンプル2

入力:K = 18、M = 40、N = 40

出力:1484

説明:kが18である場合、ロボットは、ボックス(35、37)を入力することができ、3 + 3 + 5 + 7 = 18理由。
3 + 3 + 5 + 8 = 19しかし、それは、ボックス(35、38)を入力することができません。

注意:

0 <= M <= 50
0 <= N <= 50
、0 <= K <= 100


範囲で、座標の桁はkに等しい未満である:BOOL配列G [] []メンテナンスとタイトルサーチテンプレートは、到達することができるグリッド条件をグリッドに到達することができます。最初のデジタルサムは、座標とDFSまたはBFSを使用して前処理したが、ANSによって横断されることができ、それぞれが、ANS ++に入る、あなたが入力することができます正方形の数を表します。

#include <bits/stdc++.h>
using namespace std;
bool g[60][60];
int n, m, k, ans;
typedef pair<int, int> P;
int d[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

int main(){
    cin >> k >> m >> n;
    memset(g, false, sizeof(g)); 
    for(int i=0; i<m; i++)
        for(int j=0; j<n; j++){
            g[i][j] = true;
            int x = i, y = j;
            int t = 0;
            while(x){
                t += x%10;
                x /= 10;
            }
            while(y){
                t += y%10;
                y /= 10;
            }
            if(t>k)  // 预处理
                g[i][j] = false;
        }
    queue<P> q;
    q.push((P){0, 0});
    g[0][0] = false;
    ans = 1;
    while(!q.empty()){
        P u = q.front();
        q.pop();
        for(int i=0; i<4; i++){
            int tx = u.first+d[i][0];
            int ty = u.second+d[i][1];
            if(g[tx][ty] && tx>=0 && tx<m && ty>=0 && ty<n){
                ans++;
                g[tx][ty] = false;
                q.push((P){tx, ty});
            }
        }
    }
    cout << ans;
    return 0;
}

おすすめ

転載: www.cnblogs.com/gdgzliu/p/11619472.html