leetcode——单词搜索

 单词搜索


给定一个二维网格和一个单词,找出该单词是否存在于网格中。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

示例:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

给定 word = "ABCCED", 返回 true
给定 word = "SEE", 返回 true
给定 word = "ABCB", 返回 false

提示:

board 和 word 中只包含大写和小写英文字母。
1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3
通过次数108,459提交次数249,098

代码

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

猜你喜欢

转载自blog.csdn.net/katrina1rani/article/details/108715985
今日推荐