[leetcode] 79. Word Search @ python

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.

解法

DFS. 遍历网格, 找到word[0]首字母的位置, 从这个位置起, 看能否找到一条路径能拼成word, 需要将已经访问过的位置进行标记.

代码

class Solution:
    def exist(self, board, word):
        """
        :type board: List[List[str]]
        :type word: str
        :rtype: bool
        """
        # edge case
        if not board: return False
        r, c = len(board), len(board[0])
        for i in range(r):
            for j in range(c):
                if board[i][j] == word[0] and self.dfs(board, word, i, j):
                    return True
                    
        return False
                    
    def dfs(self, board, word, i, j):
        # all the letters are checked
        if len(word) == 0:
            return True
        if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or board[i][j] != word[0]:
            return False
        temp = board[i][j]
        # mark the visited cell
        board[i][j] = '#'
        res  = self.dfs(board, word[1:], i-1, j) or self.dfs(board, word[1:], i+1, j) \
               or self.dfs(board, word[1:], i, j-1) or self.dfs(board, word[1:], i, j+1)
        board[i][j] = temp
        return res
            

你可能感兴趣的:(Leetcode)