fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void fastio() {
  5. ios_base::sync_with_stdio(false);
  6. cin.tie(nullptr);
  7. cout.tie(nullptr);
  8. }
  9.  
  10. int n;
  11. vector<vector<char>> grid;
  12. vector<vector<bool>> vis;
  13.  
  14. bool valid(int x, int y) {
  15. return (x >= 0 && x < n && y >= 0 && y < n);
  16. }
  17.  
  18. int count_x = 0;
  19. void dfs(int x, int y) {
  20. if (!valid(x, y) || grid[x][y] == '.' || vis[x][y])
  21. return;
  22.  
  23. vis[x][y] = true;
  24. if (grid[x][y] == 'x')
  25. count_x++;
  26.  
  27. dfs(x + 1, y);
  28. dfs(x - 1, y);
  29. dfs(x, y + 1);
  30. dfs(x, y - 1);
  31. }
  32.  
  33. int count_ships() {
  34. int cnt = 0;
  35. for (int i = 0; i < n; i++) {
  36. for (int j = 0; j < n; j++) {
  37. if ((grid[i][j] == 'x' || grid[i][j] == '@') && !vis[i][j]) {
  38. count_x = 0;
  39. dfs(i, j);
  40. if (count_x > 0)
  41. cnt++;
  42. }
  43. }
  44. }
  45. return cnt;
  46. }
  47.  
  48. void solve(int t) {
  49. cin >> n;
  50.  
  51. grid.resize(n, vector<char>(n));
  52. vis.assign(n, vector<bool>(n, false));
  53. for (int i = 0; i < n; ++i)
  54. for (int j = 0; j < n; ++j)
  55. cin >> grid[i][j];
  56.  
  57. count_x = 0;
  58. cout << "Case " << t << ": " << count_ships() << '\n';
  59.  
  60. grid.clear();
  61. vis.clear();
  62. }
  63.  
  64. int main() {
  65. fastio();
  66. int t = 1;
  67. cin >> t;
  68. for (int i = 1; i <= t; ++i)
  69. solve(i);
  70. return 0;
  71. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Case 1: 0