Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Color Map by Sim0000
def color_map(field):
# recursive search
def search(n):
if n == N: return True
for c in (1,2,3,4):
if all(color[i] != c for i in connect[n] if i < n):
color[n] = c
if search(n + 1): return True
return False
# initialize
width, height = len(field[0]), len(field)
# make connect dictionary, connect[i] is set of adjacent of i
connect = {}
for y, row in enumerate(field):
for x, n in enumerate(row):
if n not in connect: connect[n] = set()
for x0, y0 in [(x-1,y), (x+1,y), (x,y-1), (x,y+1)]:
if 0 <= x0 < width and 0 <= y0 < height and field[y0][x0] != n:
connect[n].add(field[y0][x0])
# search
N = len(connect)
color = [0]*N
search(0)
return color
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
NEIGHS = ((-1, 0), (1, 0), (0, 1), (0, -1))
COLORS = (1, 2, 3, 4)
ERROR_NOT_FOUND = "Didn't find a color for the country {}"
ERROR_WRONG_COLOR = "I don't know about the color {}"
def checker(func, region):
user_result = func(region)
if not isinstance(user_result, (tuple, list)):
print("The result must be a tuple or a list")
return False
country_set = set()
for i, row in enumerate(region):
for j, cell in enumerate(row):
country_set.add(cell)
neighbours = []
if j < len(row) - 1:
neighbours.append(region[i][j + 1])
if i < len(region) - 1:
neighbours.append(region[i + 1][j])
try:
cell_color = user_result[cell]
except IndexError:
print(ERROR_NOT_FOUND.format(cell))
return False
if cell_color not in COLORS:
print(ERROR_WRONG_COLOR.format(cell_color))
return False
for n in neighbours:
try:
n_color = user_result[n]
except IndexError:
print(ERROR_NOT_FOUND.format(n))
return False
if cell != n and cell_color == n_color:
print("Same color neighbours.")
return False
if len(country_set) != len(user_result):
print("Excess colors in the result")
return False
return True
Oct. 15, 2014
Comments: