|
| 1 | +from copy import copy |
| 2 | +from typing import List, Set, Tuple |
| 3 | +from algorithms.backtracking.word_search.point import Point |
| 4 | +from algorithms.backtracking.word_search.constants import PLANE_LIMITS |
| 5 | +from datastructures.trees.trie import Trie, TrieNode |
| 6 | + |
| 7 | + |
| 8 | +class WordSearch: |
| 9 | + def __init__(self, puzzle): |
| 10 | + """ |
| 11 | + Creates a new word search object |
| 12 | + :ivar self.width will be the length of the width for this word-search object, which is the length of the |
| 13 | + first item in the list. |
| 14 | + It is assumed that all items will have same length |
| 15 | + :ivar self.height will be the height of thw object, in this case, just the length of the list |
| 16 | + :param puzzle: the puzzle which will be a tuple of words separated by newline characters |
| 17 | + """ |
| 18 | + self.rows = puzzle.split() |
| 19 | + self.width = len(self.rows[0]) |
| 20 | + self.height = len(self.rows) |
| 21 | + |
| 22 | + def search(self, word): |
| 23 | + """ |
| 24 | + Searches for a word in the puzzle |
| 25 | + :param word: word to search for in puzzle |
| 26 | + :return: the points where the word can be found, None if the word does not exist in the puzzle |
| 27 | + :rtype: Point |
| 28 | + """ |
| 29 | + # creates a generator object of points for each letter in the puzzle |
| 30 | + positions = (Point(x, y) for x in range(self.width) for y in range(self.height)) |
| 31 | + for pos in positions: |
| 32 | + for plane_limit in PLANE_LIMITS: |
| 33 | + result = self.find_word( |
| 34 | + word=word, position=pos, plane_limit=plane_limit |
| 35 | + ) |
| 36 | + if result: |
| 37 | + return result |
| 38 | + return None |
| 39 | + |
| 40 | + def find_word(self, word, position, plane_limit): |
| 41 | + """ |
| 42 | + Finds the word on the puzzle given the word itself, the position (Point(x, y)) and the plane limit |
| 43 | + :param word: the word we are currently searching for, e.g python |
| 44 | + :param position: the current point on cartesian plan for the puzzle e.g Point(0, 0) |
| 45 | + :param plane_limit: the current plan limit, e.g Point(1, 0) |
| 46 | + :return: The Point where the whole word can be found |
| 47 | + :rtype: Point |
| 48 | + """ |
| 49 | + # create a copy of the passed in position |
| 50 | + curr_position = copy(position) |
| 51 | + for let in word: |
| 52 | + if self.find_char(coord_point=curr_position) != let: |
| 53 | + return |
| 54 | + curr_position += plane_limit |
| 55 | + return position, curr_position - plane_limit |
| 56 | + |
| 57 | + def find_char(self, coord_point): |
| 58 | + """ |
| 59 | + finds a character on the given puzzle |
| 60 | + :param coord_point: The current copy of the current point position being sought through |
| 61 | + :return: |
| 62 | + """ |
| 63 | + if coord_point.x < 0 or coord_point.x >= self.width: |
| 64 | + return |
| 65 | + if coord_point.y < 0 or coord_point.y >= self.height: |
| 66 | + return |
| 67 | + # return the particular letter in the puzzled |
| 68 | + return self.rows[coord_point.y][coord_point.x] |
| 69 | + |
| 70 | + |
| 71 | +def find_strings(grid: List[List[str]], words: List[str]) -> List[str]: |
| 72 | + """ |
| 73 | + Finds the strings in the grid |
| 74 | + Args: |
| 75 | + grid (List[List[str]]): The grid to search through |
| 76 | + words (List[str]): The words to search for |
| 77 | + Returns: |
| 78 | + List[str]: The words that were found in the grid |
| 79 | + """ |
| 80 | + trie = Trie() |
| 81 | + for word in words: |
| 82 | + trie.insert(word) |
| 83 | + |
| 84 | + rows_count, cols_count = len(grid), len(grid[0]) |
| 85 | + result = [] |
| 86 | + |
| 87 | + visited: Set[Tuple[int, int]] = set() |
| 88 | + |
| 89 | + # directions to move in the grid horizontally and vertically from a given cell |
| 90 | + directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] |
| 91 | + |
| 92 | + # lambda function to check if the current cell is within the grid |
| 93 | + is_cell_within_grid = lambda r, c: 0 <= r < rows_count and 0 <= c < cols_count |
| 94 | + |
| 95 | + def dfs(row: int, col: int, node: TrieNode, path: str): |
| 96 | + """ |
| 97 | + Depth-first search to find the words in the grid |
| 98 | + Args: |
| 99 | + row (int): The row of the current cell |
| 100 | + col (int): The column of the current cell |
| 101 | + node (TrieNode): The current node in the trie |
| 102 | + path (str): The current path of the word |
| 103 | + """ |
| 104 | + # check if the current node is a word |
| 105 | + if node.is_end: |
| 106 | + result.append(path) |
| 107 | + # prevent duplicates |
| 108 | + node.is_end = False |
| 109 | + # prune the word from the trie |
| 110 | + trie.remove_characters(path) |
| 111 | + |
| 112 | + # We don't want to exit early, we want to continue searching for other words this is because from this node |
| 113 | + # other words can potentially be found. |
| 114 | + |
| 115 | + # mark visited |
| 116 | + visited.add((row, col)) |
| 117 | + |
| 118 | + # explore neighbors |
| 119 | + for dr, dc in directions: |
| 120 | + new_row, new_col = row + dr, col + dc |
| 121 | + # three specific conditions must be met before calling dfs recursively |
| 122 | + # 1. the new cell must be within the grid |
| 123 | + # 2. the new cell must not be visited |
| 124 | + # 3. the new cell must be a child of the current node |
| 125 | + if ( |
| 126 | + is_cell_within_grid(new_row, new_col) |
| 127 | + and (new_row, new_col) not in visited |
| 128 | + and grid[new_row][new_col] in node.children |
| 129 | + ): |
| 130 | + new_character = grid[new_row][new_col] |
| 131 | + dfs( |
| 132 | + new_row, new_col, node.children[new_character], path + new_character |
| 133 | + ) |
| 134 | + |
| 135 | + # backtracking, remove the visited cell |
| 136 | + # so that we can explore other paths |
| 137 | + # By removing it, we ensure the cell is available again when the algorithm explores a completely different path |
| 138 | + # from a different starting point |
| 139 | + visited.remove((row, col)) |
| 140 | + |
| 141 | + for row in range(rows_count): |
| 142 | + for col in range(cols_count): |
| 143 | + char = grid[row][col] |
| 144 | + if char in trie.root.children: |
| 145 | + dfs(row, col, trie.root.children[char], char) |
| 146 | + |
| 147 | + return result |
0 commit comments