Last active
June 4, 2023 11:27
-
-
Save defanator/748dd34add66ab0e9acc6203f0350432 to your computer and use it in GitHub Desktop.
word search in python
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/bin/env python3 | |
# vim:sw=4:ts=4:et: | |
# | |
# based on https://www.tutorialspoint.com/word-search-in-python | |
BOARD = [ | |
['A', 'B', 'C', 'E'], | |
['S', 'F', 'R', 'S'], | |
['A', 'D', 'E', 'E'], | |
['T', 'I', 'G', 'R'], | |
] | |
class Solution(object): | |
def exist(self, board, word, res_board=None): | |
n = len(board) | |
m = len(board[0]) | |
for i in range(n): | |
for j in range(m): | |
if word[0] == board[i][j]: | |
if self.find(board, word, i, j, res_board=res_board): | |
return True | |
return False | |
def find(self, board, word, row, col, i=0, res_board=None): | |
#print(f'find called: word={word} row={row} col={col} i={i}') | |
if i == len(word): | |
return True | |
if row >= len(board) or row < 0 or col >= len(board[0]) or col < 0 or word[i] != board[row][col]: | |
return False | |
board[row][col] = '*' | |
res = ( | |
self.find(board, word, row+1, col, i+1, res_board=res_board) or | |
self.find(board, word, row-1, col, i+1, res_board=res_board) or | |
self.find(board, word, row, col+1, i+1, res_board=res_board) or | |
self.find(board, word, row, col-1, i+1, res_board=res_board) | |
) | |
board[row][col] = word[i] | |
if res and res_board: | |
res_board[row][col] = word[i] | |
return res | |
def print_board(self, board): | |
for row in board: | |
print(' '.join(row)) | |
def empty_board_from(self, board): | |
res = [] | |
num_rows = len(board) | |
num_cols = len(board[0]) | |
for i in range(num_rows): | |
res.append([]) | |
for j in range(num_cols): | |
res[i].append('.') | |
return(res) | |
if __name__ == '__main__': | |
ws = Solution() | |
print('Source board:') | |
ws.print_board(BOARD) | |
for word in ('SEE', 'CAT', 'TIGR', 'TIGER', 'ERDT', 'AFER'): | |
empty_board = ws.empty_board_from(BOARD) | |
rc = ws.exist(BOARD, word, res_board=empty_board) | |
print(f'Searching for {word}: {rc}') | |
if rc: | |
ws.print_board(empty_board) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment