import sys
from queue import Queue # 导入队列所需模块
def bfs():
global n, m, length, k
while k > 0 and (not q.empty()):
t = q.get()
for i in range(4):
x = t[0] + fx[i]
y = t[1] + fy[i]
if x >= 0 and x < n and y >= 0 and y < m and case[x][y] != 'g': # 判断周围空地是否超出边界以及是否已经种草
case[x][y] = 'g'
q.put((x, y))
length -= 1 # 利用length来控制每一轮的长草
if length == 0: # 当length为0时,代表完成了一轮的长草,k-1,并且length变为下一轮需要长草的数量
length = q.qsize()
k -= 1
n, m = sys.stdin.readline().split()
n = int(n) # 行数
m = int(m) # 列数
case = [] # 模拟地图
q = Queue()
for i in range(n):
s = sys.stdin.readline().strip()
ss = []
for j in range(len(s)):
a = s[j]
if a == 'g':
q.put((i, j))
ss.append(a)
case.append(ss)
length = q.qsize() # 初始化length代表开始的草地上长草数量
k = int(sys.stdin.readline().strip())
# 方向引导数组
fx = [0, 1, -1, 0]
fy = [1, 0, 0, -1]
bfs()
for i in range(n):
for j in range(m):
print(case[i][j], end='')
print()
使用List列表解题:
import sys
def bfs():
global n, m, length, k
while k > 0 and length > 0:
t = q[0]
for i in range(4):
x = t[0] + fx[i]
y = t[1] + fy[i]
if x >= 0 and x < n and y >= 0 and y < m and case[x][y] != 'g':
case[x][y] = 'g'
q.append((x, y))
length -= 1
q.remove(q[0])#利用每次长草完成后列表的remove操作进行更新
if length == 0:
length = len(q)
k -= 1
n, m = sys.stdin.readline().split()
n = int(n) # 行数
m = int(m) # 列数
case = [] # 模拟地图
q = []
# qend = 0
# qfront = 0
for i in range(n):
s = sys.stdin.readline().strip()
ss = []
for j in range(len(s)):
a = s[j]
if a == 'g':
q.append((i, j))
ss.append(a)
case.append(ss)
length = len(q)
k = int(sys.stdin.readline().strip())
# 方向引导数组
fx = [0, 1, -1, 0]
fy = [1, 0, 0, -1]
bfs()
for i in range(n):
for j in range(m):
print(case[i][j], end='')
print()
两者区别在于使用 Queue 耗时 3000 ms , 使用 list 模拟仅消耗 54 ms 所以大家使用 Python 编写代码的时候还是使用 List 尽量避免 Queue 的使用。