问题:
1.)如果world[y][x] != 'land'
条件为真,则为return 0
。谁现在拥有这个价值?此if-end statement
之后的代码是否仍会被评估?
2.)有8条size = size + ...
行,代表图块的5个邻居(5,5)。所以使用(5,5)并使用size = size + continent_size(world, x-1, y-1)
行,我知道它会计算(4,4),在这种情况下是o
。我的问题,因为(4,4)o
是water
,它仍会计数(3,3),(2,2)等,或者它会在它之后停止(4, 4)并计算下一个size = size + ...
行?
# These are just to make the map easier for me to read.
# "M" is visually more dense then "o".
M = 'land'
o = 'water'
world = [[o,o,o,o,o,o,o,o,o,o,o],
[o,o,o,o,M,M,o,o,o,o,o],
[o,o,o,o,o,o,o,o,M,M,o],
[o,o,o,M,o,o,o,o,o,M,o],
[o,o,o,M,o,M,M,o,o,o,o],
[o,o,o,o,M,M,M,M,o,o,o],
[o,o,o,M,M,M,M,M,M,M,o],
[o,o,o,M,M,o,M,M,M,o,o],
[o,o,o,o,o,o,M,M,o,o,o],
[o,M,o,o,o,M,o,o,o,o,o],
[o,o,o,o,o,o,o,o,o,o,o]]
def continent_size world, x, y
if world[y][x] != 'land'
# Either it's water or we already counted it,
# but either way, we don't want to count it now.
return 0
end
# So first we count this tile...
size = 1
world[y][x] = 'counted land'
# ...then we count all of the neighboring eight tiles
# (and, of course, their neighbors by way of the recursion).
size = size + continent_size(world, x-1, y-1)
size = size + continent_size(world, x , y-1)
size = size + continent_size(world, x+1, y-1)
size = size + continent_size(world, x-1, y )
size = size + continent_size(world, x+1, y )
size = size + continent_size(world, x-1, y+1)
size = size + continent_size(world, x , y+1)
size = size + continent_size(world, x+1, y+1)
size
end
puts continent_size(world, 5, 5)
答案 0 :(得分:0)
1)值0将由调用该函数的人保留,假设
a = continent_size(world, x, y)
现在a为0.其余的语句将不会被评估,因为return语句将结束该方法的执行。
2)行size = ...之间没有return语句,所以它将执行所有这些
答案 1 :(得分:0)
1)0值将返回到here's how you'd do it
metehod instace,它会调用您询问的实例。 continent_size
语句的其余部分将不会被评估,因为该方法已经向其调用者返回0。
2)它会停止'在if-end
之后(因为它是水,它只会返回(4,4)
)并计算下一个0
行确实