-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path079_word-search.py
58 lines (48 loc) · 1.8 KB
/
079_word-search.py
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Given a 2D board and a word, find if the word exists in the grid.
# The word can be constructed from letters of sequentially adjacent cell,
# where "adjacent" cells are those horizontally or vertically neighboring.
# The same letter cell may not be used more than once.
# Example:
# board =
# [
# ['A','B','C','E'],
# ['S','F','C','S'],
# ['A','D','E','E']
# ]
# Given word = "ABCCED", return true.
# Given word = "SEE", return true.
# Given word = "ABCB", return false.
# ----------------------------------------------
# Ideas:
# Considerations:
# Complexity: time, space
# ----------------------------------------------
class Solution:
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
def backtrack(board, nrows, ncols, r, c, word, idx):
if idx >= len(word):
return True
if r < 0 or r >= nrows or c < 0 or c >= ncols:
return False
if word[idx] != board[r][c]:
return False
char, board[r][c] = board[r][c], '.' # mark current char
result = backtrack(board, nrows, ncols, r - 1, c, word, idx + 1) or \
backtrack(board, nrows, ncols, r + 1, c, word, idx + 1) or \
backtrack(board, nrows, ncols, r, c - 1, word, idx + 1) or \
backtrack(board, nrows, ncols, r, c + 1, word, idx + 1)
board[r][c] = char
return result
if len(board) == 0 or len(board[0]) == 0:
return False
nrows, ncols = len(board), len(board[0])
for r in range(nrows):
for c in range(ncols):
if backtrack(board, nrows, ncols, r, c, word, 0):
return True
return False