题目描述 79. Word Search •Total Accepted: 85823 •Total Submissions: 357336 •Difficulty: Medium 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. For example, Given board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] word = "ABCCED", -> returns true, word = "SEE", -> returns true, word = "ABCB", -> returns false. 给定一个数组, 和单词,查找该单词是否在数组中出现。数组中每个字符只能用一次,而且保证字符之间是连续的, 即上下左右查找。
思考: 这道题第一想到的就是回溯法了。 就像迷宫问题一样,依次遍历数组中的字符作为起点,开始进行查找,
每次查找有四个方向, 由于每个字符在一次查找中只能出现一次, 所以使用一个数组来标识。 代码如下: class Solution(object): def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ if len(board) == 0 or len(board[0]) == 0: return False used = [[False for j in range(len(board[0]))] for i in range(len(board))] for i in range(0, len(board)): for j in range(0, len(board[0])): if self.back(board, word, 0, i, j, used): return True return False def back(self, board, word, step, i, j, used): if step == len(word): return True if i < 0 or j < 0 or i >= len(board) or j >= len(board[0])
or used[i][j] or board[i][j] != word[step]: return False used[i][j] = True res = self.back(board, word, step+1, i+1,j, used)
or self.back(board, word, step+1, i, j+1, used)
or self.back(board, word, step+1, i-1,j, used)
or self.back(board, word, step+1, i, j-1, used) used[i][j] = False return res