[PAT]1091 Acute Stroke (30分)(樣例5未過原因)

一、題目:

二、分析

使用BFS。

三、代碼

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

int M, N, L, T;

struct core {
    bool value;
    bool visited;
    int z, x, y;
    core(bool value, bool visited, int z, int x, int y) : value(value), visited(visited), z(z), x(x), y(y) {}
};

vector<vector<vector<core *>>> cores;

bool judge(int z, int x, int y) {
    return !(z < 0 || z >= L || x < 0 || x >= M || y < 0 || y >= N || !cores[z][x][y]->value ||
             cores[z][x][y]->visited);
}

int ans = 0;
int dz[6] = {0, 0, 0, 0, 1, -1};
int dx[6] = {-1, 1, 0, 0, 0, 0};
int dy[6] = {0, 0, -1, 1, 0, 0};

void BFS() {
    for (int i = 0; i < L; i++) {
        for (int j = 0; j < M; j++) {
            for (int k = 0; k < N; k++) {
                if (!cores[i][j][k]->visited && cores[i][j][k]->value) {
                    int cnt = 0;
                    queue<core *> q;
                    q.push(cores[i][j][k]);
                    cores[i][j][k]->visited = true;
                    cnt++;
                    while (!q.empty()) {
                        core *temp_c = q.front();
                        q.pop();
                        for (int l = 0; l < 6; l++) {
                            if (judge(temp_c->z + dz[l], temp_c->x + dx[l], temp_c->y + dy[l])) {
                                q.push(cores[temp_c->z + dz[l]][temp_c->x + dx[l]][temp_c->y + dy[l]]);
                                cores[temp_c->z + dz[l]][temp_c->x + dx[l]][temp_c->y + dy[l]]->visited = true;
                                cnt++;
                            } else {
                                continue;
                            }
                        }
                    }
                    if (cnt >= T) {
                        ans += cnt;
                    }
                } else {
                    continue;
                }
            }
        }
    }
}

int main() {
    cin >> M >> N >> L >> T;
    for (int i = 0; i < L; i++) {
        vector<vector<core *>> temp1(M);
        cores.push_back(temp1);
        for (int j = 0; j < M; j++) {
            vector<core *> temp2(N);
            cores[i].push_back(temp2);
            for (int k = 0; k < N; k++) {
                int a;
                cin >> a;
                core *temp3 = new core(a == 1, false, i, j, k);
                cores[i][j].push_back(temp3);
            }
        }
    }

    BFS();
    cout << ans;
    return 0;
}

四、注意

樣例5未過原因:搜索時只搜索了前後左右和下層的相鄰節點。
每次搜索時都要搜索節點周圍的6個節點。因爲可能存在這種情況:某一個滿足題意的區域節點先向下一層延伸再在同層延伸,然後再往上延伸。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章