Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
recursive conditionals solution in Clear category for Color Map by Tinus_Trotyl
def color_map(region): # color_map(region)
global MX, MY, N
MX, MY, N = len(region[0]), len(region), 0
map = [[[0, 0] for x in range(MX)] for y in range(MY)] # make a map for countries and their colors
print(map)
for y in range(MY):
for x in range(MX):
N = max(N, region[y][x] + 1) # count number of countries in N
map[y][x][0] = region[y][x] # and mark the countries on the map
if paint(0, 1, map): # try if we can paint it
colors = [0 for i in range(N)] # then get the color sequence from te map
for y in range(MY):
for x in range(MX):
colors[map[y][x][0]] = map[y][x][1]
return colors # and return them colors.
else:
return ["Sorry, I can't find any solution for you."]
def paint(country, color, map): # conditional function paint
global MX, MY, N
if country == N: return True # Yes, we've done it !!! we're true.
lmap = map[:] # Make a copy of map for local use.
for y in range(MY): # Look for all sectors of the map if...
for x in range(MX):
if lmap[y][x][0] == country:
for dx, dy in ((0, 1), (1, 0), (0, -1), (-1, 0)):
if 0 <= x+dx < MX and 0 <= y+dy < MY:
if lmap[y+dy][x+dx][0] != country:
if lmap[y+dy][x+dx][1] == color: # ...there is an adjacent country with the same color,
return False # then we're false.
lmap[y][x][1] = color # Else go on with this color omn the local map.
for n in 1, 2, 3, 0, 1, 2, 3: # For all 4 colors, the same color last or first...
if paint(country + 1, ((color - 1 + n) % 4) + 1, lmap): # And if we can paint with one of these colors ...
map = lmap # update the global map with our local map...
return True # and see your true colors shining through.
return False # Else, sorry, we can't color it, we can't be true.
June 20, 2017
Comments: