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

    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:
        def exist(self, board, word):
            """
            :type board: List[List[str]]
            :type word: str
            :rtype: bool
            """
            def dfs(i,j,pos):
                if(i<0 or j<0 or i==len(board) or j==len(board[0])):
                    return False
                if pos == len(word):
                    return True
                if board[i][j] == word[pos]:
                    board[i][j] = None
                    temp = dfs(i+1,j,pos+1) or dfs(i-1,j,pos+1) or dfs(i,j+1,pos+1) or dfs(i,j-1,pos+1)
                    board[i][j] = word[pos]
                    return temp
    
            for i in range(len(board)):
                for j in range(len(board[0])):
                    if board[i][j]==word[0]:
                        if len(word)==1:
                            return True
                        if dfs(i,j,0):
                            return True
            return False
    
  • 相关阅读:
    typescript
    js-解决安卓手机软键盘弹出后,固定定位布局被顶上移问题
    vue
    js
    Object.assgin基本知识与相关深浅拷贝
    js-工具方法(持续更新)
    vue
    vue
    git
    css
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9733243.html
Copyright © 2011-2022 走看看