這裏是查找所有單詞驚奇一(醜)算法:時間驚奇的複雜求解
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
這是什麼算法的大O運行?我相信這是O((N²)!)
,但我不確定。
要小心d的長度。這是一個常數,但是當您通過d進行搜索時,它會乘以要解析的呼叫數量。所以我認爲這可能會使大字典(可能會在實踐中使用)變得更糟。 – seaotternerd