Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link
Given an m x n
grid of characters board
and a string word
, return true
if word
exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example 1:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" Output: true
Example 2:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" Output: true
Example 3:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" Output: false
Constraints:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board
andword
consists of only lowercase and uppercase English letters.
Follow up: Could you use search pruning to make your solution faster with a larger board
?
內容目錄
TogglePython
# time complexity: O(c*3^l)
# space complexity: O(l)
from typing import List
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
def backtrack(suffix: str, r: int, c: int):
if len(suffix) == 0:
return True
if not (0 <= r < ROW and 0 <= c < COL) or suffix[0] != board[r][c]:
return False
result = False
originalChar = board[r][c]
board[r][c] = "#"
for dr,dc in ([1,0],[0,1],[-1,0],[0,-1]):
result = backtrack(suffix[1:], r+dr, c+dc)
if result:
break
board[r][c] = originalChar
return result
ROW = len(board)
COL = len(board[0])
for row in range(ROW):
for col in range(COL):
if backtrack(word, row, col):
return True
return False
board = [["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"]]
word = "ABCCED"
print(Solution().exist(board, word))