LC 79 - Word Search
LC 79 - Word Search
Question
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:
1
2
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true
Example 2:
1
2
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true
Example 3:
1
2
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false
Constraints:
m == board.lengthn = board[i].length1 <= m, n <= 61 <= word.length <= 15boardandwordconsists of only lowercase and uppercase English letters.
Follow up: Could you use search pruning to make your solution faster with a larger board?
Links
Question here and solution here
Solution
concept
We use backtracking on every cells. Each backtracking is essentially a DFS on 4 directions.
code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
ROW, COL = len(board), len(board[0])
path = set()
def dfs(r, c, idx):
if idx == len(word):
return True
if (r < 0 or c < 0 or
r >= ROW or c >= COL or
board[r][c] != word[idx] or
(r,c) in path):
return False
path.add((r,c))
ans = (dfs(r + 1, c, idx + 1) or
dfs(r - 1, c, idx + 1) or
dfs(r, c + 1, idx + 1) or
dfs(r , c - 1, idx + 1))
path.remove((r,c))
return ans
for r in range(ROW):
for c in range(COL):
exist = dfs(r, c, 0)
if exist:
return True
return False
Complexity
time: $O(m*4^n)$, where $m$ is the number of cells in the board and $n$ is the length of the word.
space: $O(n)$
This post is licensed under CC BY 4.0 by the author.


