当前位置:   article > 正文

长草蓝桥杯模拟赛python解法(BFS)_蓝桥杯长草问题python

蓝桥杯长草问题python

题目描述

 

 解题思路

当遍历周围的所有元素时,我们就要想到用bfs。用到bfs就要用到队列,而且这种遍历周围的也需要构建方向字典。具体看代码注释,注释写的很详细

代码

  1. from collections import deque
  2. #输初始化数据
  3. maps = []
  4. q = deque()
  5. direct={(0,1),(1,0),(0,-1),(-1,0)}#草能蔓延的四个方向
  6. #读入数据
  7. n,m=map(int,input().strip().split())
  8. for _ in range(n):
  9. maps.append(list(input()))
  10. k=int(input())
  11. #遍历maps,如果有草则添加进队列
  12. for i in range(n):
  13. for j in range(m):
  14. if maps[i][j]=='g':
  15. q.append((i,j))
  16. #bfs广度优先遍历
  17. def bfs():
  18. t=len(q)
  19. #遍历当前队列里所有存储有草的地方
  20. while t>0:
  21. temp=q.popleft()
  22. x,y=temp[0],temp[1]#当前有草的坐标
  23. for dx,dy in direct:
  24. #有草的地方像四处蔓延
  25. nx=x+dx
  26. ny=y+dy
  27. if nx>=0 and ny>=0 and nx<n and ny<m and maps[nx][ny]=='.':
  28. #判断是否越界或者是否有草
  29. #没越界或是空地则添加进队列好下一次遍历并种上草
  30. maps[nx][ny]='g'
  31. q.append((nx,ny))
  32. t-=1
  33. #调用bfs的次数,既是长草几个月
  34. for _ in range(k):
  35. bfs()
  36. for i in maps:
  37. print(''.join(i))

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

闽ICP备14008679号