慕尼黑5688855
我的回答与其他人一样,但是我会发布它,因为它看起来比其他Python解决方案更快,从更快地设置字典。(我对John Fouhy的解决方案进行了检查。)设置完成后,解决的时间是噪音。grid = "fxie amlo ewbx astu".split()nrows, ncols = len(grid), len(grid[0])# A dictionary word that could be a solution must use only the grid's# letters and have length >= 3. (With a case-insensitive match.)import re
alphabet = ''.join(set(''.join(grid)))bogglable = re.compile('[' + alphabet + ']{3,}$', re.I).match
words = set(word.rstrip('\n') for word in open('words') if bogglable(word))prefixes = set(word[:i] for word in words for i in range(2, len(word)+1))def solve():
for y, row in enumerate(grid):
for x, letter in enumerate(row):
for result in extending(letter, ((x, y),)):
yield resultdef extending(prefix, path):
if prefix in words:
yield (prefix, path)
for (nx, ny) in neighbors(path[-1]):
if (nx, ny) not in path:
prefix1 = prefix + grid[ny][nx]
if prefix1 in prefixes:
for result in extending(prefix1, path + ((nx, ny),)):
yield resultdef neighbors((x, y)):
for nx in range(max(0, x-1), min(x+2, ncols)):
for ny in range(max(0, y-1), min(y+2, nrows)):
yield (nx, ny)样品用法:# Print a maximal-length word and its path:print max(solve(), key=lambda (word, path): len(word))编辑:过滤少于3个字母的单词。编辑2:我很好奇为什么Kent Fredric的Perl解决方案更快; 事实证明,使用正则表达式匹配而不是一组字符。在Python中做同样的事情会使速度提高一倍。