Joseph L. Casale
2/29/2008 2:55:00 PM
I am trying to understand how the following code knows not to count a tile =
that has been previously counted, its an example from Chris Pine's Learn to=
Program from Pragmatic Bookshelf. I understand how the first size =3D size=
+ ... recursively starts counting, but for example when you go to the next=
size =3D ... how is the possible overlap accounted for?
Thanks!
jlc
# These are just to make the map
# easier for me to read. "M" is
# visually more dense than "o".
M =3D ' land'
o =3D ' water'
world =3D [[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] !=3D ' 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 =3D 1
world[y][x] =3D ' counted land'
# ...then we count all of the
# neighboring eight tiles (and,
# of course, their neighbors by
# way of the recursion).
size =3D size + continent_size(world, x-1, y-1)
size =3D size + continent_size(world, x , y-1)
size =3D size + continent_size(world, x+1, y-1)
size =3D size + continent_size(world, x-1, y )
size =3D size + continent_size(world, x+1, y )
size =3D size + continent_size(world, x-1, y+1)
size =3D size + continent_size(world, x , y+1)
size =3D size + continent_size(world, x+1, y+1)
size
end