40分求调
查看原帖
40分求调
764499
Unreal414楼主2024/3/20 21:09
/*@Unreal414 版权所有!!!*/
#include <bits/stdc++.h>
using namespace std;
int n, m, result = 0, direction[4][2] = {{ 0, 1 }, { 0, -1 }, { -1, 0 }, { 1, 0 }};
char v[104][104];
bool visited[104][104] = { false };
queue <pair <int, int> > q;
void solve(int x, int y) {
	q.push(make_pair(x, y));
	visited[x][y] = true;
	while (q.size()) {
		int tx = q.front().first, ty = q.front().second;
		q.pop();
		for (int i = 0; i < 4; i++) {
			int targetX = tx + direction[i][0], targetY = ty + direction[i][1];
			if (targetX < 1 || targetX > n || targetY < 1 || targetY > n) continue;
			if (visited[targetX][targetY] || v[targetX][targetY] == '0') continue;
			q.push(make_pair(targetX, targetY));
			visited[targetX][targetY] = true;
		}
	}
}
int main() {
	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++)
			v[i][j] = '0';
	cin >> n >> m;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++)
			cin >> v[i][j];
	}
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++)
			if (!visited[i][j] && v[i][j] != '0') {
				solve(i, j);
				result++;
			}
	cout << result << "\n";
	return 0;
}
2024/3/20 21:09
加载中...