AcWing 1097. 池塘计数

以你之姓@ 2024-04-08 12:53 155阅读 0赞

AcWing 1097. 池塘计数

原题链接

AcWing 1097. 池塘计数

思路

在这里插入图片描述

代码

  1. #include<bits/stdc++.h>
  2. #define int long long
  3. #define rep(i, a, b) for(int i=a;i<b;++i)
  4. #define Rep(i, a, b) for(int i=a;i>b;--i)
  5. #define x first
  6. #define y second
  7. using namespace std;
  8. typedef pair<int, int> PII;
  9. const int N = 1005, M = N*N;
  10. int n,m;
  11. char g[N][N];
  12. PII q[M];
  13. bool st[N][N];
  14. inline int read(){
  15. int s=0,w=1;
  16. char ch=getchar();
  17. while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
  18. while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
  19. return s*w;
  20. }
  21. void put(int x) {
  22. if(x<0) putchar('-'),x=-x;
  23. if(x>=10) put(x/10);
  24. putchar(x%10^48);
  25. }
  26. void bfs(int sx, int sy){
  27. // 数组模拟队列
  28. int hh=0, tt=0;
  29. q[0]={sx, sy};
  30. st[sx][sy]=true;
  31. // 队列非空
  32. while(hh<=tt){
  33. // 操作队头元素
  34. PII t=q[hh++];
  35. rep(i, t.x-1, t.x+2){
  36. rep(j, t.y-1, t.y+2){
  37. // 去除中心位置
  38. if (i == t.x && j == t.y) continue;
  39. // 去除出界位置
  40. if (i < 0 || i >= n || j < 0 || j >= m) continue;
  41. // 去除陆地与已被标记的位置
  42. if (g[i][j] == '.' || st[i][j]) continue;
  43. // 将周围是W且尚未标记的元素入队
  44. q[ ++ tt] = {i, j};
  45. // 标记
  46. st[i][j] = true;
  47. }
  48. }
  49. }
  50. }
  51. signed main(){
  52. ios::sync_with_stdio(false);
  53. cin.tie(0);
  54. cout.tie(0);
  55. n=read(), m=read();
  56. rep(i, 0, n){
  57. scanf("%s", g[i]);
  58. }
  59. int cnt=0;
  60. rep(i, 0, n){
  61. rep(j, 0, m){
  62. // 为W且尚未标记
  63. if(g[i][j]=='W'&&!st[i][j]){
  64. bfs(i, j);
  65. cnt++;
  66. }
  67. }
  68. }
  69. printf("%lld", cnt);
  70. return 0;
  71. }

参考文献
AcWing 1097. 池塘计数y总视频讲解
AcWing 1097. 池塘计数y总代码

原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,155人围观)

还没有评论,来说两句吧...

相关阅读

    相关 算法:【池塘取水】

    题目:假设有一个池塘,里面有无穷多的水,现有两个空水壶,容积分别为5升和6升,如何只用这2个水壶从池塘里取得3升的水. 题解: 第一步:先取来6升水,倒进5升桶的水桶

    相关 1097. C语言成绩排名

    时间限制:1Sec内存限制:128MB通过:90提交:375 题目描述 已知n个学生的学号(8位数)、姓名和C语言成绩,请按照规定输出他们的排名。排序规则: 如果成绩不相同