0
点赞
收藏
分享

微信扫一扫

僵尸来袭。

西红柿上校 2022-03-14 阅读 89
c++

题目描述
​ 9102 年,小明和李华正在怀旧的玩植物大战僵尸重置版,重置版多了一个道具—卫星地图,使用此道具后就能知道后院外(n 行 m 列)的每个格子有多少个僵尸, 0 代表这个格子上没有僵尸,其余数代表僵尸的个数。若某一个格子上有僵尸,且在这个格子上下左右的某个格子上也有僵尸,那么他们为同一波僵尸,现求后院外还有多少波僵尸。

输入
​ 第一行一个整数 n,m (5≤n,m≤100)。

​ 接下来 n 行 m 列,由数字组成的 n×m 的方阵。

输出
​ 输出剩余僵尸有几波。

样例输入
5 6
0 1 2 3 4 0
1 0 0 0 0 0
2 9 3 0 2 4
0 0 2 0 2 8
1 0 0 0 0 0
样例输出
4
数据规模与约定
​ 时间限制:1 s

​ 内存限制:256 M

​ 100% 的数据保证 5≤n,m≤100
方法一:利用队列

#include <iostream>
#include <queue>
using namespace std;
int n, m, map[105][105];
int dir[4][2] = {1, 0, 0, 1, -1, 0, 0, -1};
struct node {
	int x, y;
};

int main() {
	queue<node> que;
	cin >> n >> m;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cin >> map[i][j];
		}
	}
	int ans = 0;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			if (map[i][j] != 0) {
				ans++;
				que.push({ i,j });
				map[i][j] = 0;
				while (!que.empty()) {
					node temp = que.front();
					que.pop();
					for (int i = 0; i < 4; i++) {
						int x = temp.x + dir[i][0];
						int y = temp.y + dir[i][1];
						if (map[x][y] != 0) {
							map[x][y] = 0;
							que.push({ x,y });
						}
					}
				}
			}
		}
	}
	cout << ans << endl;
	return 0;
}

方法二:递归

#include <iostream>
using namespace std;

int n, m, mmap[105][105], ans;
int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};

void func(int x0, int y0) {
    for (int i = 0; i < 4; i++) {
        int x = x0 + dir[i][0];
        int y = y0 + dir[i][1];
        if (mmap[x][y] != 0) {
            mmap[x][y] = 0;
            func(x, y);
        }
    }
}

int main() {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            cin >> mmap[i][j];
        }
    }
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            if (mmap[i][j] != 0) {
                ans++;
                mmap[i][j] = 0;
                func(i, j);
            }
        }
    }
    cout << ans << endl;
    return 0;
}
举报

相关推荐

0 条评论