搜索--PAT.A1091[BFS]

来源:互联网 发布:阿里云ecs安装lamp 编辑:程序博客网 时间:2024/06/05 15:44

题目:https://www.patest.cn/contests/pat-a-practise/1091

题目本身不难,类似于非连通图的BFS()标准遍历代码,从每一点向六个方向扩展即可。

感悟:做的过程,有一点让我好崩溃,判断候选点是否满足条件,如果把判断语句放在BFS()函数内部,则提交会显示所有测试点段错误,而当把判断语句与调用函数实现时,则正确了。好像放在内部,因为有三层循环,系统栈承受不了爆栈的样子【对比PAT.A1456,只调用一次BFS(),这种方式就可以了;】

先就这样搁着吧,进度不能等了,快复试了!

#include<cstdio>#include<queue>using namespace std;int M, N, L, T;int map[1290][130][65] = { 0 }; //记录点位bool mark[1290][130][65] = { false }; //是否访问int sum = 0; //1 的总数struct point {    int a, b, c;};int go[][3] = {//坐标转换数组【六个方向】    1, 0, 0,    -1, 0, 0,    0, 1, 0,    0, -1, 0,    0, 0, 1,    0, 0, -1};queue<point> que;bool judge(int x, int y, int z) {//判断点是否满足    if (x < 0 || x >= N || y < 0 || y >= M || z < 0 || z >= L)    //不再区域内        return false;    if (true == mark[x][y][z] || 0 == map[x][y][z]) return false;        //已访问过 or 不是1        return true;}int BFS(int nx, int ny, int nz) {    while (false == que.empty()) que.pop(); //清空    point temp1; //起始点入队列    temp1.a = nx;    temp1.b = ny;    temp1.c = nz;    mark[nx][ny][nz] = true;    que.push(temp1);    int tempSum = 0;    while (false == que.empty()) {        point now = que.front();//出队列        point temp;        que.pop();        tempSum++;        //搜索6个方向        for (int i = 0; i < 6; i++) {            int x = now.a + go[i][0];            int y = now.b + go[i][1];            int z = now.c + go[i][2];/*就是这两句,放在这儿就显示段错误        if (true == mark[x][y][z] || 0 == map[x][y][z]) continue;if (x < 0 || x >= N || y < 0 || y >= M || z < 0 || z >= L)                  continue;       */                      if (judge(x, y, z)) {//这样实现就能通过 [崩溃脸]                temp.a = x;                temp.b = y;                temp.c = z;                mark[x][y][z] = true;                que.push(temp); //入队列            }        }//for    }//while    return tempSum;}int main() {    /*    注意: L M N 三者的关系,楼层L 在循环最外层    */    scanf("%d%d%d%d", &N, &M, &L, &T);    for (int k = 0; k < L; k++) {        for (int i = 0; i < N; i++) {            for (int j = 0; j < M; j++) {                scanf("%d", &map[i][j][k]);                mark[i][j][k] = false;            }        }    }    sum = 0;    for (int k = 0; k < L; k++) {        for (int i = 0; i < N; i++) {            for (int j = 0; j < M; j++) {                if (1 == map[i][j][k] &&false==mark[i][j][k]) {                    //类似于非连通图的遍历                    int temp = BFS(i, j, k);                    if (temp >= T)                        sum += temp;                }            }        }    }    printf("%d\n", sum);    return 0;}
0 0