当前位置:   article > 正文

BFS算法 蓝桥杯长草问题

BFS算法 蓝桥杯长草问题

题目描述

小明有一块空地,他将这块空地划分为 nn 行 mm 列的小块,每行和每列的长度都为 1。

小明选了其中的一些小块空地,种上了草,其他小块仍然保持是空地。

这些草长得很快,每个月,草都会向外长出一些,如果一个小块种了草,则它将向自己的上、下、左、右四小块空地扩展,

这四小块空地都将变为有草的小块。请告诉小明,kk 个月后空地上哪些地方有草。

解题思路

见 BFS算法入门(走迷宫问题)

代码

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. char a[10000][10000];
  4. struct node {
  5. int x;
  6. int y;
  7. };
  8. queue<node> q;
  9. int dx[] = {0, 1, 0, -1}; //左右上下
  10. int dy[] = {1, 0, -1, 0}; //左右上下
  11. int main() {
  12. int n, m;
  13. cin >> n >> m;
  14. for (int i = 0; i < n; i++) {
  15. for (int j = 0; j < m; j++) {
  16. cin >> a[i][j];
  17. if (a[i][j] == 'g') {
  18. node newNode;
  19. newNode.x = i;
  20. newNode.y = j;
  21. q.push(newNode);
  22. }
  23. }
  24. }
  25. int k;
  26. cin >> k;
  27. while (k--) {
  28. int len = q.size();
  29. while (len--) {
  30. int x = q.front().x;
  31. int y = q.front().y;
  32. for (int i = 0; i < 4; i++) {
  33. int tx = x + dx[i]; //周边节点的X轴
  34. int ty = y + dy[i]; //周边节点的y轴
  35. if (a[tx][ty] == '.') {
  36. a[tx][ty] = 'g';
  37. node newNode;
  38. newNode.x = tx;
  39. newNode.y = ty;
  40. q.push(newNode);
  41. }
  42. }
  43. q.pop();
  44. }
  45. }
  46. for (int i = 0; i < n; i++)
  47. for (int j = 0; j < m; j++)
  48. cout << a[i][j];
  49. cout << endl;
  50. return 0;
  51. }

 

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

闽ICP备14008679号