美文网首页
PAT甲级A1091---广度优先搜索

PAT甲级A1091---广度优先搜索

作者: 1nvad3r | 来源:发表于2020-08-13 10:27 被阅读0次

1091 Acute Stroke (30分)

1091
分析:

给出一个三维数组,若干个相邻的“1”称为一个块。如果某个块中“1”的个数不低于T个,则这个块称为“卒中核心区”。现在需要求解所有卒中核心区中的1的个数之和。
枚举三维数组每一个位置,如果为0,则跳过;如果为1,则使用bfs查询与该位置相邻的6个位置。

C++:
#include <cstdio>
#include <queue>

using namespace std;

struct Node {
    int x, y, z;
} temp;

int n, m, slice, T;//n*m矩阵,共有slice层,T为卒中核心区1的个数下限
int pixel[1290][130][61];
bool inq[1290][130][61];
int X[6] = {0, 0, 0, 0, 1, -1};
int Y[6] = {0, 0, 1, -1, 0, 0};
int Z[6] = {1, -1, 0, 0, 0, 0};

bool judge(int x, int y, int z) {
    if (x >= n || x < 0 || y >= m || y < 0 || z >= slice || z < 0) {
        return false;
    }
    if (pixel[x][y][z] == 0 || inq[x][y][z] == true) {
        return false;
    }
    return true;
}

int bfs(int x, int y, int z) {
    int cnt = 0;//当前块1的个数
    queue<Node> q;
    temp.x = x;
    temp.y = y;
    temp.z = z;
    q.push(temp);
    inq[x][y][z] = true;
    while (!q.empty()) {
        Node top = q.front();
        q.pop();
        cnt++;
        for (int i = 0; i < 6; i++) {
            int newX = top.x + X[i];
            int newY = top.y + Y[i];
            int newZ = top.z + Z[i];
            if (judge(newX, newY, newZ) == true) {
                temp.x = newX;
                temp.y = newY;
                temp.z = newZ;
                q.push(temp);
                inq[newX][newY][newZ] = true;
            }
        }
    }
    if (cnt >= T) {
        return cnt;
    } else {
        return 0;
    }
}

int main() {
    scanf("%d%d%d%d", &n, &m, &slice, &T);
    for (int z = 0; z < slice; z++) {
        for (int x = 0; x < n; x++) {
            for (int y = 0; y < m; y++) {
                scanf("%d", &pixel[x][y][z]);
            }
        }
    }
    int res = 0;
    for (int z = 0; z < slice; z++) {
        for (int x = 0; x < n; x++) {
            for (int y = 0; y < m; y++) {
                if (pixel[x][y][z] == 1 && inq[x][y][z] == false) {
                    res += bfs(x, y, z);
                }
            }
        }
    }
    printf("%d\n", res);
    return 0;
}

相关文章

  • PAT甲级A1091---广度优先搜索

    1091 Acute Stroke (30分) 分析: 给出一个三维数组,若干个相邻的“1”称为一个块。如果某个块...

  • 搜索

    一、深度优先搜索 图深度优先遍历、深度优先搜索算法求有权图两点最短路径 二、广度优先搜索 图广度优先遍历、广度优先...

  • 图的遍历

    结构 深度优先搜索 广度优先搜索

  • 深度优先搜索和广度优先搜索

    一、深度优先搜索 二、广度优先搜索

  • 深度优先广度优先

    深度优先搜索 广度优先搜索(队列实现)

  • LeetCode广度、深度优先搜索

    广度优先搜索 广度优先搜索(也称宽度优先搜索,缩写BFS即即Breadth First Search)是连通图的一...

  • 广度优先搜索算法

    上一篇简书小编分享了“深度优先搜索”算法,今天小编继续分享下“广度优先搜索”算法。 一、何为“广度优先搜索” 广度...

  • 算法与数据结构 之 搜索算法

    搜索分为广度优先搜索、深度优先搜索、A*算法。 一、广度优先算法(BFS) 1.1、基本实现和特性:BFS是从一个...

  • 广度优先搜索算法(BFS)

    广度优先搜索算法(BFS) 标签(空格分隔): algorithm 1.广度优先搜索算法(Breadth Firs...

  • 6.2 BFS与DFS

    广度优先搜索(BFS)自顶点s的广度优先搜索(Breadth-First Search)(1) 访问顶点s(2) ...

网友评论

      本文标题:PAT甲级A1091---广度优先搜索

      本文链接:https://www.haomeiwen.com/subject/soxbdktx.html