所以,我有一份表格[['0','0','0','0','0'],
['0','0','0','0','0'],
['1','0','0','0','0'],
['1','0','0','0','0'],
['0','0','0','0','0']]
我希望“1”周围的“0”在一个步骤后变为“1”,就像这样。在
^{pr2}$
经过足够的步骤,所有的“0”都变成了“1”。在
我的代码如下def simulate_bushfire(list, steps):
for _ in range(steps):# iterates through the number of steps
for y in range(len(initial_bushfire[0])):
for x in range(len(initial_bushfire)): #for all y coordinates possible in the file
if initial_bushfire[y][x] =='1':# looks for cells that has '1' in it
for a in range(x-1,x+2): #looks at the neighbour of the cell that has'1' in it (x coordinates)
for b in range(y-1,y+2):#looks at the neighbour of the cell that has'1' in it (y coordinates)
if a<0 or b<0 or b>=len(initial_bushfire[0]) or a>=len(initial_bushfire):# if neighbour is outside the border of the map,
#code will ignore to avoid errors like list out of range
continue
if initial_bushfire[b][a]=='':# if there's an empty string (no tree)
continue # ignore this as well (no trees to burn )
if initial_bushfire[b][a]=='0': #if there is a '0' in the file (there is a tree)
initial_bushfire[b][a]='1'# change the '0' to a '1' (tree on fire)
return (initial_bushfire)
但这似乎对一步来说太多了。我似乎不明白为什么,但我想是因为这条线for a in range(x-1,x+2): #looks at the neighbour of the cell that has'1' in it (x coordinates)
for b in range(y-1,y+2):#looks at the neighbour of the cell that has'1' in it (y coordinates)
如果有人能指导我这段代码,我将非常感激。在