LeetCode---79. Word Search

题目

给出一个m * n的二维数组,里面的元素是字母,另给出一个单词,找出是否可以利用二维数组相邻的字母来构造单词。相邻意味着4个方向:上下左右。如:

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.

Python题解:

class Solution(object):
    def exist(self, board, word):
        """
        :type board: List[List[str]]
        :type word: str
        :rtype: bool
        """
        if not board or not board[0]:
            return False

        visited = [[False for _ in range(len(board[0]))] for _ in range(len(board))]

        for i in range(len(board)):
            for j in range(len(board[0])):
                if word[0] == board[i][j]:
                    if self.dfs(board, word, visited, i, j, 0):
                        return True
        return False

    def isValid(self, board, i, j):
        if i < 0 or j < 0 or i >= len(board) or j >= len(board[0]):
            return False
        return True

    def dfs(self, board, word, visited, i, j, k):
        # print(i, j, k, visited, board[i][j], word[k])
        if visited[i][j]:
            return False

        if word[k] != board[i][j]:
            return False

        if k == len(word) - 1:
            return True

        visited[i][j] = True
        directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
        for direction in directions:
            ni, nj = i + direction[0], j + direction[1]
            if self.isValid(board, ni, nj):
                if self.dfs(board, word, visited, ni, nj, k + 1):
                    return True
        visited[i][j] = False

你可能感兴趣的:(leetcode,leetcode,数组,dfs)