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
     
  • 相关阅读:
    【转】C#中的虚方法
    【转】ASP.NET 2.0中Page事件的执行顺序
    OWC ChartSpace控件的使用
    Ext对基本类型的扩展
    OWC PivotTable的使用方法
    .net中线程同步的典型场景和问题(1)
    python中使用汉字
    如何取消后台线程的执行
    yaffs2根文件系统的构建过程
    Fuck self.delegate = self
  • 原文地址:https://www.cnblogs.com/prmlab/p/7146555.html
Copyright © 2011-2022 走看看