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
     
  • 相关阅读:
    【杭电】[1874]畅通工程续
    【杭电】[2544]最短路
    【杭电】[1087]Super Jumping! Jumping! Jumping!
    【HPU】[1689]MZY寻宝
    【杭电】[1495]非常可乐
    【杭电】[1242]Rescue
    【杭电】[1787]GCD Again
    【算法】欧拉函数——小于n的数中与n互质数的数目
    【HPU】[1738]Stack ? Queue ?
    【HPU】[1737]老王特警队
  • 原文地址:https://www.cnblogs.com/prmlab/p/7146555.html
Copyright © 2011-2022 走看看