Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Color Map by pohmelie
import collections
def region_to_map_generator(r):
for y, row in enumerate(r):
for x, v in enumerate(row):
yield (x, y), v
def build_graph(field):
neighbour = ((-1, 0), (1, 0), (0, 1), (0, -1))
fronts = collections.deque((((0, 0),),))
viewed = {(0, 0)}
m = collections.defaultdict(set, ((field[0, 0], set()),))
while fronts:
front = fronts.pop()
n = field[front[0]]
nfront = ()
for p in front:
for dp in neighbour:
np = tuple(map(sum, zip(p, dp)))
if np in field:
if field[np] == n:
if np not in viewed:
nfront += (np,)
else:
m[n].add(field[np])
if np not in viewed:
fronts.append((np,))
viewed.add(np)
if nfront:
fronts.append(nfront)
return m
def bind_colors(graph, available_colors, colors=None):
colors = colors or collections.ChainMap()
if len(colors) == len(graph):
yield colors
node = next(iter(graph.keys() - colors.keys()))
for color in available_colors - set(map(lambda n: colors.get(n, None), graph[node])):
# yield from bind_colors(graph, available_colors, colors.new_child({node: color})) # 3.4
ncolors = colors.new_child()
ncolors[node] = color
yield from bind_colors(graph, available_colors, ncolors)
def color_map(region):
field = dict(region_to_map_generator(region))
graph = build_graph(field)
colors = next(bind_colors(graph, set(range(1, 5))))
return tuple(map(colors.get, sorted(colors)))
Dec. 15, 2014