(我不太确定这个问题是否符合StackOverflow。)
这是问题22的第二部分:
Molecule fabrication always begins with just a single electron, e, and applying
replacements one at a time, just like the ones during calibration.
For example, suppose you have the following replacements:
e => H
e => O
H => HO
H => OH
O => HH
If you'd like to make HOH, you start with e, and then make the following
replacements:
e => O to get O
O => HH to get HH
H => OH (on the second H) to get HOH
So, you could make HOH after 3 steps. Santa's favorite molecule, HOHOHO,
can be made in 6 steps.
How long will it take to make the medicine? Given the available replacements and
the medicine molecule in your puzzle input, what is the fewest number of steps
to go from e to the medicine molecule?
这是我的Python 3解决方案:
import re
from collections import defaultdict
transitions = defaultdict(list)
inv_transitions = dict()
endpoints = set()
with open('AC_Day-19.txt') as f:
rules, string = f.read().split('\n\n')
lines = rules.split('\n')
for line in lines:
a, _, b = line.split()
inv_transitions[b] = a
units = re.compile(r'[A-Z][a-z]*')
tokens = units.findall(string)
temp_string = string
steps = 0
while True:
if temp_string == "e":
break
for j in sorted(inv_transitions, key=len, reverse=True):
if j in temp_string:
temp_string = temp_string.replace(j, inv_transitions[j], 1)
steps += 1
break
else:
continue
print(steps)
基本上,在解析给定数据之后,代码会不断检查字符串和逆字典值之间是否匹配,从每种情况下的最长值开始,并用逆字典中的相应值替换。
我得到答案,但我不相信。是否有可能证明该算法在任何给定的设置中总是会得到正确的答案?
(例如,对于给定的设置,最短的路径是否需要一个中间步骤,我们需要在有更长的一个可用时替换较短的一个字符串片段?
或者,难道不是这种方法在某些时候陷入困境,我们必须提前采取中间步骤吗?如果是这样,我应该如何调整算法?)