【leetcode】(python) 79. Word Search单词搜索

单词搜索

  • Description
  • Example
  • 题意
  • 解题思路
    • code

79. Word Search Medium

Description

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.

题意

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

该单词可以由顺序相邻的单元的字母构成,其中“相邻”单元是水平或垂直相邻的单元。 相同的字母单元格不得多次使用。

解题思路

单词要由2D板的上下左右的相邻顺序组成,所以搜索时如果不满足条件要回退一步,可想到深度优先遍历的回溯算法。又题目要求相同的字母单元格不得多次使用,所以每次搜索前要先置从该位置过去的字母不可访问,待该次搜索完成后要恢复原值,因为可能后续搜索时该字母会被访问到。

code

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        def dfs(i,j,word):
            if len(word) == 0:
                return True
            
            # up
            if i>0 and board[i-1][j] == word[0]:
                temp = board[i][j]
                board[i][j] = None
                if dfs(i-1,j,word[1:]):
                    return True
                board[i][j] = temp
                
            # down
            if i0 and board[i][j-1] == word[0]:
                temp = board[i][j]
                board[i][j] = None
                if dfs(i,j-1,word[1:]):
                    return True
                board[i][j] = temp
            
            # right
            if j < len(board[0])-1 and board[i][j+1] == word[0]:
                temp = board[i][j]
                board[i][j] = None
                if dfs(i,j+1,word[1:]):
                    return True
                board[i][j] = temp
                
            return False
                
        for i in range(len(board)):
            for j in range(len(board[0])):
                if board[i][j] == word[0]:
                    if dfs(i,j,word[1:]):
                        return True
        return False

你可能感兴趣的:(LeetCode)