这是一个在 Boggle 中查找所有单词的(丑陋的)算法:
d = {'cat', 'dog', 'bird'}
grid = [
['a', 'd', 'c', 'd'],
['o', 'c', 'a', 't'],
['a', 'g', 'c', 'd'],
['a', 'b', 'c', 'd']
]
found = {}
N = 4
def solve(row, col, prefix):
if prefix in d and prefix not in found:
found[prefix] = True
print prefix
for i in xrange(max(0, row - 1), min(N, row + 2)):
for j in xrange(max(0, col - 1), min(N, col + 2)):
c = grid[i][j]
if c != '#' and not (row == i and col == j):
grid[i][j] = '#'
solve(i, j, prefix + c)
grid[i][j] = c
for row in xrange(N):
for col in xrange(N):
c = grid[row][col]
grid[row][col] = '#'
solve(row, col, c)
grid[row][col] = c
该算法的 Big-O 运行时间是多少?我相信它是O((N²)!)
,但我不确定。