Created
April 2, 2010 15:28
-
-
Save jxcl/353259 to your computer and use it in GitHub Desktop.
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
def recursive_word_is_valid(word, board, pos): | |
""" | |
Arguments: | |
- `word`: the remainder of the word to be searched. | |
- `board`: the current board. | |
- `pos`: the current position in the board. | |
""" | |
if board[pos[0]][pos[1]] == word[0]: | |
char = board[pos[0]][pos[1]] | |
board[pos[0]][pos[1]] = -1 | |
for x_mod in range(-1,2): | |
for y_mod in range(-1,2): | |
found = recursive_word_is_valid(word[:1], board, (pos[0]+x_mod, pos[1]+y_mod)) | |
if found: | |
return True | |
# The next character was not found. | |
# Leave the board unchanged. | |
board[pos[0]][pos[1]] = char | |
return False | |
else: | |
return False | |
def scan_for_first_letter(word, board): | |
""" | |
Scans the board for all occurences of the first letter, then begins the recursive | |
search on each of them. | |
Arguments: | |
- `word`: The word to be searched for. | |
""" | |
char = word[0] | |
for x in range(len(board)): | |
for y in range(len(board[x])): | |
if board[x][y] == char: | |
return (x, y) | |
return None | |
def validate_word(word, board): | |
"""Returns true if word can be made using the letters | |
on the board. | |
Arguments: | |
- `word`: The word to be validated. | |
- `board`: The current board. | |
""" | |
pos = self.scan_for_first_letter(word, board) | |
result = recursive_word_is_valid(word, board, pos) | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment