Last active
August 29, 2015 14:04
-
-
Save lwiecek/77e7a46a74c57113bd70 to your computer and use it in GitHub Desktop.
Word puzzle - DFS with generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/local/bin/python3 | |
N = 4 | |
DICTIONARY = set([ | |
'A', | |
'AB', | |
'ABC', | |
'ABCDEDCB', | |
'ABCDEFAFEDCDEDCB' | |
]) | |
def dfs(N, i, j, board, path=[], visited=None, results=None): | |
if visited is None: | |
visited = {} | |
if results is None: | |
results = set() | |
if not visited.get((i, j)): | |
visited[i, j] = True | |
path.append(board[i, j]) | |
word = ''.join(path) | |
if (word in DICTIONARY) and (word not in results): | |
results.add(word) | |
yield word | |
for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]: | |
if (0 <= i + di < N) and (0 <= j + dj < N): | |
yield from dfs(N, i + di, j + dj, board, path, visited, results) | |
path.pop() | |
visited[(i, j)] = False | |
def gen_board(N): | |
from itertools import product | |
board = {} | |
for i, j in product(range(N), range(N)): | |
board[i, j] = 'ABCDEF'[(i + j) % 6] | |
return board | |
board = gen_board(N) | |
for i in range(N): | |
for j in range(N): | |
print(board[i, j], end=' ') | |
print() | |
results = dfs(N, 0, 0, board) | |
for word in results: | |
print(word) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment