题解
[USACO10OCT] Lake Counting S
1 条题解
-
0
1. 解题思路
扫描所有水格,每遇到未标记水格就增加一个水塘,并用广度优先搜索标记其八方向连通块。
2. 坑点和注意事项
n、m≤100。对角也相邻,入队时把水格改为干地,保证每格只处理一次。
3. 复杂度
- 时间复杂度:O(nm)。
- 空间复杂度:O(nm)。
/* 思路:扫描所有水格,每遇到未标记水格就增加一个水塘,并用广度优先搜索标记其八方向连通块。 关键规则与坑点:n、m≤100。对角也相邻,入队时把水格改为干地,保证每格只处理一次。 时间复杂度:O(nm)。空间复杂度:O(nm)。 */ #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, m; cin >> n >> m; string a[100]; for (int i = 0; i < n; i++) cin >> a[i]; int ans = 0; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (a[i][j] == 'W') { ans++; queue<pair<int, int>> q; q.push({i, j}); a[i][j] = '.'; while (!q.empty()) { int x = q.front().first, y = q.front().second; q.pop(); for (int dx = -1; dx <= 1; dx++) for (int dy = -1; dy <= 1; dy++) { int u = x + dx, v = y + dy; if (u >= 0 && u < n && v >= 0 && v < m && a[u][v] == 'W') { a[u][v] = '.'; q.push({u, v}); } } } } cout << ans << '\n'; }
- 1