I have a two-dimensional map of land and water, like the following (l
representing land and w
representing water).
lllwwwlll
lllwllllw
lllllllww
lllllllll
For each land tile, I want to know its distance from the nearest water tile. Moving horizontally, vertically, and diagonally all count as a distance of one.
321www111
321w1111w
3211121ww
322222111
Right now I am using an algorithm like so:
foreach tile in map
if isWater(tile)
tile.distanceFromWater = 0
else
radius = 1
while !hasWaterAround(tile, radius)
radius++
tile.distanceFromWater = radius
This approach works, but it rather slow, especially when there are very few water tiles.
Is there a faster algorithm for finding the distance of each land tile from water?