Word search
Given a two-dimensional grid and a word, find out whether the word exists in the grid.
Words must be in alphabetical order and formed by letters in adjacent cells, where "adjacent" cells are those that are adjacent horizontally or vertically. Letters in the same cell are not allowed to be reused.
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
prompt:
Only uppercase and lowercase English letters are contained in board and word.
1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3
Passed 108,459 Submitted 249,098
Code
class Solution:
def equal_c(self, board, mark, c, row, col):
if row >= len(board) or row < 0:
return False
if col >= len(board[row]) or col < 0:
return False
if mark[row][col] == 0 and board[row][col]==c:
return True
return False
def exist(self, board, word):
word_clist = list(word)
for row in range(len(board)):
for col in range(len(board[row])):
if word_clist[0]!=board[row][col]:
continue
if len(word_clist)==1:
return True
mark = [[0] * len(item) for item in board] # 用来标记是否已经选中
choose_list = [''] * len(word_clist)
cur_word_i = 0
choose_list[0] = (row, col)
mark[row][col] = 1
cur_word_i += 1
temp_store = [[] for i in range(len(word_clist))] # 暂存每一位未遍历的点
temp_store[cur_word_i].extend([(row, col+1),(row+1, col),(row, col-1),(row-1, col)])
while cur_word_i > 0:
if len(temp_store[cur_word_i])==0:
cur_word_i -= 1
pre_pos = choose_list[cur_word_i]
mark[pre_pos[0]][pre_pos[1]] = 0
choose_list[cur_word_i] = ''
continue
pos = temp_store[cur_word_i][0]
temp_store[cur_word_i].remove(pos)
if self.equal_c(board, mark, word_clist[cur_word_i], pos[0], pos[1]): #匹配上,进行下一位置搜索
if cur_word_i == len(word_clist) - 1:
return True
choose_list[cur_word_i] = pos
mark[pos[0]][pos[1]] = 1
cur_word_i += 1
temp_store[cur_word_i].extend([(pos[0], pos[1]+1),(pos[0]+1, pos[1]),(pos[0], pos[1]-1),
(pos[0]-1, pos[1])])
return False