| 9 | 9 | |
| 10 | 10 | class WordSearch: |
| 11 | 11 | def __init__(self, puzzle): |
| 12 | | pass |
| 12 | # Edge Case: Handle empty puzzle |
| 13 | if not puzzle: |
| 14 | self.puzzle = [] |
| 15 | self.height = 0 |
| 16 | self.width = 0 |
| 17 | else: |
| 18 | self.puzzle = puzzle |
| 19 | self.height = len(puzzle) |
| 20 | # Edge Case: Handle irregular grid dimensions |
| 21 | self.width = len(puzzle[0]) if self.height > 0 else 0 |
| 13 | 22 | |
| 14 | 23 | def search(self, word): |
| 15 | | pass |
| 24 | # Edge Case: Handle empty word |
| 25 | if not word: |
| 26 | return None |
| 27 | |
| 28 | # Edge Case: Handle empty puzzle |
| 29 | if not self.puzzle: |
| 30 | return None |
| 31 | |
| 32 | # Edge Case: Handle word longer than puzzle dimensions |
| 33 | if len(word) > self.height and len(word) > self.width: |
| 34 | return None |
| 35 | |
| 36 | # Define all 8 directions: right, left, down, up, down-right, down-left, up-right, up-left |
| 37 | directions = [ |
| 38 | (0, 1), # right |
| 39 | (0, -1), # left |
| 40 | (1, 0), # down |
| 41 | (-1, 0), # up |
| 42 | (1, 1), # down-right |
| 43 | (1, -1), # down-left |
| 44 | (-1, 1), # up-right |
| 45 | (-1, -1) # up-left |
| 46 | ] |
| 47 | |
| 48 | for y in range(self.height): |
| 49 | for x in range(self.width): |
| 50 | for dy, dx in directions: |
| 51 | # Check if word fits in this direction |
| 52 | end_x = x + (len(word) - 1) * dx |
| 53 | end_y = y + (len(word) - 1) * dy |
| 54 | |
| 55 | # Edge Case: Check bounds |
| 56 | if end_x < 0 or end_x >= self.width or end_y < 0 or end_y >= self.height: |
| 57 | continue |
| 58 | |
| 59 | # Check if word matches in this direction |
| 60 | found = True |
| 61 | for i in range(len(word)): |
| 62 | curr_x = x + i * dx |
| 63 | curr_y = y + i * dy |
| 64 | # Edge Case: Handle case sensitivity |
| 65 | if self.puzzle[curr_y][curr_x].upper() != word[i].upper(): |
| 66 | found = False |
| 67 | break |
| 68 | |
| 69 | if found: |
| 70 | # Return start and end points (0-indexed) |
| 71 | return (Point(x, y), Point(end_x, end_y)) |
| 72 | |
| 73 | # Edge Case: Word not found |
| 74 | return None |
| 75 | |
| 76 | # Handled Edge Cases: empty word, empty puzzle, word longer than puzzle dimensions, out of bounds, case sensitivity, word not found |