This commit is contained in:
2020-01-09 16:49:01 -05:00
parent e84f4c6efc
commit 607dc88bd3

View File

@@ -1,4 +1,4 @@
from copy import deepcopy
from copy import copy
colors_max = None
@@ -27,6 +27,15 @@ class Node(object):
if len(nb.colors) == 1:
nb.set_only_color()
def get_state(self):
return list(map(copy, [self.neighbors, self.colors, self.color]))
def restore_state(self, state):
self.neighbors = state[0]
self.colors = state[1]
self.color = state[2]
def parse(input_data):
# parse the input
lines = input_data.split('\n')
@@ -66,11 +75,25 @@ def branch(nodes, color):
return next_nodes
# This is where we actually have to iterate and branch.
min_node.color = min_node.colors.pop()
for nb in min_node.neighbors:
nb.colors.discard(min_node.color)
nb.neighbors.remove(min_node)
return search(next_nodes, color)
print("THIS IS WHERE THE MAGIC HAPPENS.")
for min_node_color in list(min_node.colors):
try:
states = [n.get_state for n in next_nodes]
state = min_node.get_state()
min_node.colors.remove(min_node_color)
min_node.color = min_node_color
for nb in min_node.neighbors:
nb.colors.discard(min_node_color)
nb.neighbors.remove(min_node)
return search(next_nodes, color)
except ValueError:
print("RESTORE: {color=} did not work for {n}.")
min_node.restore_state(state)
for node, state in zip(next_nodes, states):
node.restore_state(state)
raise Exception("We should not have gotten here.")
def prune(nodes, color):
@@ -118,7 +141,7 @@ def search(nodes, color):
def solve_it(input_data):
global colors_max
nodes = parse(input_data)
# colors_max = 6
colors_max = 6
nodes.sort(key=lambda n: len(n.neighbors), reverse=True)
color = 0
search(list(nodes), color)