fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. typedef long long ll;
  6. typedef pair<int, int> ii;
  7.  
  8. const int INF = 1e9;
  9. const ll LINF = 1e18;
  10.  
  11. const int N = 1e3 + 5;
  12.  
  13. /* trái - phải - lên - xuống */
  14. int dx[4] = {0, 0, -1, 1};
  15. int dy[4] = {-1, 1, 0, 0};
  16.  
  17. int n, m;
  18. string s[N];
  19.  
  20. bool vis[N][N]; // vis[x][y]: ô (x, y) đã được thăm hay chưa
  21.  
  22. // Check ô (x, y) có nằm trong bảng và là ô trống
  23. bool ok(int x, int y) {
  24. return (0 <= x && x < n && 0 <= y && y < m && s[x][y] == '.');
  25. }
  26.  
  27. void bfs(int sx, int sy) {
  28. queue<ii> q;
  29.  
  30. vis[sx][sy] = true;
  31. q.push({sx, sy});
  32.  
  33. while (!q.empty()) {
  34. ii u = q.front(); q.pop();
  35. int x = u.first, y = u.second;
  36.  
  37. for (int i = 0; i < 4; i++) {
  38. int nx = x + dx[i], ny = y + dy[i];
  39.  
  40. if (ok(nx, ny) && !vis[nx][ny]) {
  41. vis[nx][ny] = true;
  42. q.push({nx, ny});
  43. }
  44. }
  45. }
  46. }
  47.  
  48. int main() {
  49. ios::sync_with_stdio(false);
  50. cin.tie(nullptr);
  51. cin >> n >> m;
  52.  
  53. for (int x = 0; x < n; x++) cin >> s[x];
  54.  
  55. memset(vis, 0, sizeof vis);
  56.  
  57. int ans = 0; // Số thành phần liên thông
  58. for (int x = 0; x < n; x++) {
  59. for (int y = 0; y < m; y++) {
  60. if (s[x][y] == '.' && !vis[x][y]) {
  61. ans++;
  62. bfs(x, y);
  63. }
  64. }
  65. }
  66.  
  67. cout << ans << '\n';
  68. }
Success #stdin #stdout 0.01s 5284KB
stdin
5 8
########
#..#...#
####.#.#
#..#...#
########
stdout
3