|
| 1 | +from typing import List |
| 2 | + |
| 3 | +class Solution: |
| 4 | + """ |
| 5 | + - Time Complexity: O(m*n*3^w) |
| 6 | + - m = len(board), n = len(board[0]), w = len(word) |
| 7 | + - m * n => finding start point |
| 8 | + - 3^w => There are three ways for visiting recursively until find a word |
| 9 | + - Space Complexity: O(w) |
| 10 | + - The sum of stack's space => The depth of dfs => len(word) |
| 11 | + """ |
| 12 | + def exist(self, board: List[List[str]], word: str) -> bool: |
| 13 | + m, n = len(board), len(board[0]) |
| 14 | + |
| 15 | + # DFS approach |
| 16 | + def dfs(i, j, leng): |
| 17 | + if leng == len(word): |
| 18 | + # Found! |
| 19 | + return True |
| 20 | + |
| 21 | + if not (0 <= i < m and 0 <= j < n) or board[i][j] != word[leng]: |
| 22 | + # Wrong position or Not matched |
| 23 | + return False |
| 24 | + |
| 25 | + temp = board[i][j] # Backup |
| 26 | + board[i][j] = "#" # Visited |
| 27 | + for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]: |
| 28 | + if dfs(i + dx, j + dy, leng + 1): |
| 29 | + return True |
| 30 | + board[i][j] = temp # Restore |
| 31 | + |
| 32 | + return False |
| 33 | + |
| 34 | + # Finding Start Point |
| 35 | + for i in range(m): |
| 36 | + for j in range(n): |
| 37 | + if word[0] == board[i][j]: |
| 38 | + if dfs(i, j, 0): |
| 39 | + return True |
| 40 | + |
| 41 | + return False |
| 42 | + |
| 43 | +tc = [ |
| 44 | + ([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCCED", True), |
| 45 | + ([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "SEE", True), |
| 46 | + ([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCB", False) |
| 47 | +] |
| 48 | + |
| 49 | +for i, (board, word, e) in enumerate(tc, 1): |
| 50 | + sol = Solution() |
| 51 | + r = sol.exist(board, word) |
| 52 | + print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}") |
0 commit comments