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

    https://leetcode.com/problems/word-search/#/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.

    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.

    Sol:

    Recursively call the dfs method on four directions - up, down, left, right - and check the letter the input word one by one. If certain letter meets the end conditions then False is returned. Otherwise, all letters are checked, and end conditions are not triggered, then True is returned.

    3 End Conditions:

    1) possible answer crosses the border of the board

    2)  the board does not have the letter in the word

    3) possible answer is visited - We don't trace back

    class Solution(object):
    
        def exist(self, board, word):
            """
            :type board: List[List[str]]
            :type word: str
            :rtype: bool
            """
            # dfs, recursion
            # time O(n^2 * m^2), space O(n^2)
            
            row = len(board)
            col = len(board[0])
            visited = {}
            for i in range(row):
                for j in range(col):
                    if self.dfs(board, word, i, j, visited):
                        return True
            return False
        
        # pos variable here is to check the letter in word one by one 
        def dfs(self, board, word, x, y, visited, pos = 0):
    
                # convergence condition, all letters in the word pass 
                if pos == len(word):
                    return True
                
                # end condition: cross the line
                if x < 0 or y < 0 or x >= len(board) or y >= len(board[0]):
                    return False
                
                # end condition: the board does not have the letter in the word
                if board[x][y] != word[pos]:
                    return False
                
                # end condition: the board has been checked, we don't trace back
                if visited.get((x,y)):
                    return False
    
                visited[(x,y)] = True
                res = self.dfs(board, word, x - 1, y, visited, pos + 1) 
                        or  self.dfs(board, word, x + 1, y, visited, pos + 1) 
                        or  self.dfs(board, word, x, y + 1, visited, pos + 1) 
                        or  self.dfs(board, word, x, y - 1, visited, pos + 1)
                visited[(x,y)] = False
                
                return res
     
  • 相关阅读:
    设置为自动启动的WindowService没有开机启动
    Asp.Net部署问题
    MSDTC的折磨
    C# WinForm 边框阴影窗体
    升级DotNetNuke
    常用缩写
    DotNetNuke的升级路径
    日本語文法勉強
    PostSubmitter~在WEB应用程序以外的其他程序里提交Web请求的类
    vue中的锚链接跳转问题
  • 原文地址:https://www.cnblogs.com/prmlab/p/7146555.html
Copyright © 2011-2022 走看看