Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Recursive painting solution in Clear category for Color Map by Leonix
def color_map(region, prohibited=None, country_colors={}):
""" Select a country with the least valid color choices available.
Try all valid colors for that country, prohibiting the color for all neighbours
of that country, and recursively calling self to paint the rest of the map. """
if prohibited is None:
countries_count = max(sum(region, ())) + 1
prohibited = { c: frozenset() for c in range(countries_count) }
if len(country_colors) == len(prohibited):
return [color for country, color in sorted(country_colors.items())]
country = max(prohibited.keys() - country_colors.keys(), key=lambda a:len(prohibited[a]))
for color in {1, 2, 3, 4} - prohibited[country]:
new_country_colors = country_colors.copy()
new_country_colors[country] = color
new_prohibited = prohibited.copy()
for y, row in enumerate(region):
for x, c in enumerate(row):
if c != country: continue
for xx, yy in (x-1, y), (x+1, y), (x, y+1), (x, y-1):
try: new_prohibited[region[yy][xx]] |= {color}
except IndexError: pass
try: return color_map(region, new_prohibited, new_country_colors)
except ValueError: pass
raise ValueError
Aug. 20, 2015
Comments: