当前位置:   article > 正文

蓝桥杯模拟题—长草_蓝桥杯长草c

蓝桥杯长草c

 题目描述

小明有一块空地,他将这块空地划分为 n 行 m 列的小块,每行和每列的长度都为 1。
  小明选了其中的一些小块空地,种上了草,其他小块仍然保持是空地。
  这些草长得很快,每个月,草都会向外长出一些,如果一个小块种了草,则它将向自己的上、下、左、右四小块空地扩展,这四小块空地都将变为有草的小块,其中有草的地方为1,空地为0。
  请告诉小明,k 个月后空地上哪些地方有草。

tips:队列+模拟

注:我输出的是所有草地的情况,读者可自行修改。相关STL知识详见此处

  1. #include<iostream>
  2. #include<vector>
  3. #include<queue>
  4. using namespace std;
  5. ostream &operator << (ostream& out,vector<vector<int>> a) {
  6. int sum=0;//没长草的土地数
  7. for(int i=0; i<a.size(); ++i) {
  8. for(int j=0; j<a[0].size(); ++j) {
  9. cout<<a[i][j]<<" ";
  10. if(!a[i][j])
  11. ++sum;
  12. }
  13. cout<<endl;
  14. }
  15. cout<<sum<<endl;
  16. }
  17. int main() {
  18. int n,m,k;
  19. cin>>n>>m>>k;
  20. vector<vector<int>> a(n,vector<int>(m,0));
  21. queue<pair<int,int>>q;
  22. for(int i=0; i<n; ++i)
  23. for(int j=0; j<m; ++j) {
  24. cin>>a[i][j];
  25. if(a[i][j])
  26. q.push(make_pair(i,j));
  27. }
  28. cout<<endl;
  29. for(int i=0; i<k; ++i) {
  30. queue<pair<int,int>>temp;
  31. int flag=0;
  32. while(!q.empty()) {
  33. pair<int,int> t = q.front();
  34. q.pop();
  35. if(t.first-1>=0&&!a[t.first-1][t.second]) { //上
  36. a[t.first-1][t.second]=1;
  37. temp.push(make_pair(t.first-1,t.second));
  38. flag=1;
  39. }
  40. if(t.first+1<n&&!a[t.first+1][t.second]) { //下
  41. a[t.first+1][t.second]=1;
  42. temp.push(make_pair(t.first+1,t.second));
  43. flag=1;
  44. }
  45. if(t.second-1>=0&&!a[t.first][t.second-1]) { //左
  46. a[t.first][t.second-1]=1;
  47. temp.push(make_pair(t.first,t.second-1));
  48. flag=1;
  49. }
  50. if(t.second+1<=m&&!a[t.first][t.second+1]) { //右
  51. a[t.first][t.second+1]=1;
  52. temp.push(make_pair(t.first,t.second+1));
  53. flag=1;
  54. }
  55. }
  56. if(flag)
  57. q=temp;
  58. else break;//如果没有空地可以长草了,提前结束算法
  59. }
  60. cout<<a;
  61. return 0;
  62. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/253453
推荐阅读
相关标签
  

闽ICP备14008679号