zoukankan      html  css  js  c++  java
  • 79. Word Search

    leetcod79题在矩阵中寻找某个单词

    """
    79. Word Search
    Medium
    
    Share
    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.
    """

    用深度优先搜索,首先找到首单词,因为矩阵中的单个元素只能用一次所以要记录路径,还要记录当前位置,

    class Solution(object):
        def searchWordinBoard(self, board, word, len_word, n, i, j, pathset):
            """
            :type board:list[list[str]]
            :type word:str
            :type n,i,j:int
            :type pathset:set
            :rtype:bool
            几个参数分别代表矩阵,单词,单词长度,当前字母,当前矩阵位置,已经经过的路径集合
            """
            if i<0 or j<0 or i>=len(board) or j>=len(board[0]):
                return False
            if word[n]!=board[i][j] or (i,j) in pathset:
                return False
            if n == len_word-1:
                return True
            pathset.add((i,j))
            result = self.searchWordinBoard(board, word, len_word, n+1, i-1, j, pathset) or 
                self.searchWordinBoard(board, word, len_word, n+1, i, j-1, pathset) or 
                self.searchWordinBoard(board, word, len_word, n+1, i+1, j, pathset) or 
                self.searchWordinBoard(board, word, len_word, n+1, i, j+1, pathset)
            pathset.remove((i,j))
            return result
    
    
        def exist(self, board, word):
            """
            :type board: List[List[str]]
            :type word: str
            :rtype: bool
            """
            if word == "":
                return True
            if not board or not board[0]:
                return False
            len_row, len_col = len(board), len(board[0])
            for i in range(len_row):
                for j in range(len_col):
                    if word[0] != board[i][j]:
                        continue
                    if self.searchWordinBoard(board, word, len(word), 0, i, j, set()):
                        return True
            return False
  • 相关阅读:
    服务器文档下载zip格式
    关于精度,模运算和高精的问题//19/07/14
    Luogu P2010 回文日期 // 暴力
    树形DP水题集合 6/18
    普通背包水题集合 2019/6/17
    因为时间少
    重学树状数组6/14(P3368 【模板】树状数组 2)
    Luogu P1291 [SHOI2002]百事世界杯之旅 // 易错的期望
    Luogu P4316 绿豆蛙的归宿//期望
    树剖
  • 原文地址:https://www.cnblogs.com/mangmangbiluo/p/10359894.html
Copyright © 2011-2022 走看看