【解题思路】
判断周围边界是否越界,若无越界情况在‘g'的上下左右都进行加一
【代码】
n, m = map(int, input().split())
arr = [['0' for _ in range(m+2)] for _ in range(n+2)]
str_list = []
for _ in range(n):
str_list.append(input())
for i in range(1, n+1):
for j in range(1, m+1):
arr[i][j] = str_list[i-1][j-1]
k = int(input())
new_grass = set()
for _ in range(k):
new_grass.clear()
for i in range(1, n+1):
for j in range(1, m+1):
if arr[i][j] == 'g':
if arr[i][j+1] != '0' and arr[i][j+1] != 'g':
new_grass.add((i, j+1))
if arr[i][j-1] != '0' and arr[i][j-1] != 'g':
new_grass.add((i, j-1))
if arr[i+1][j] != '0' and arr[i+1][j] != 'g':
new_grass.add((i+1, j))
if arr[i-1][j] != '0' and arr[i-1][j] != 'g':
new_grass.add((i-1, j))
for pos in new_grass:
arr[pos[0]][pos[1]] = 'g'
for i in range(1, n+1):
for j in range(1, m+1):
print(arr[i][j], end='')
print()
但上述代码会超时
针对较大规模数据的优化,我们可以使用 BFS(广度优先搜索)算法来模拟草的生长过程,以减少不必要的遍历
import sys
import os
#
from collections import deque
n,m = map(int,input().split())
arr = [['0' for _ in range(m+2)] for _ in range(n+2)]#(m+2)x(n+2)
str_list = []
for _ in range(n):
str_list.append(input())
for i in range(1,n+1):
for j in range(1,m+1):
arr[i][j] = str_list[i-1][j-1]
k = int(input())#k mounth
def bfs(arr,n,m):
directions = [(0,1),(1,0),(0,-1),(-1,0)]#定义了一个包含四个二元组的列表 directions
queue = deque()#双端队列(deque),在两端进行快速的插入和删除操作
for i in range(1,n+1):
for j in range (1,m+1):
if arr[i][j] == 'g':
queue.append((i,j))#将坐标 (i, j) 添加到队列中
for _ in range(k):
new_queue = deque()
while queue:
x,y = queue.popleft()#从队列左侧(也就是队列的首部)移除并返回一个元素。这个元素被赋值给了变量 x 和 y
for dx,dy in directions:
nx,ny = x+dx,y+dy
if 1<=nx <= n and 1<= ny <= m and arr[nx][ny]!='0' and arr[nx][ny] != 'g':
arr[nx][ny] = 'g'
new_queue.append((nx,ny))
queue = new_queue
return arr
result = bfs(arr,n,m)
for i in range(1,n+1):
for j in range(1,m+1):
print(result[i][j],end='')#在不换行的情况下输出 result[i][j] 所表示的元素
print()#通过 print() 来换行
【截图】