zoukankan      html  css  js  c++  java
  • [Leetcode]@python 79. Word Search

    题目链接

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

    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.

    题目大意

    给出一字表和词语,返回这个词语是否在字表上。字表之间只能水平和垂直相连,字表中的字符只能访问一次

    解题思路

    使用dfs来搜索,为了避免已经用到的字母被重复搜索,将已经用到的字母临时替换为'#'

    代码

    class Solution(object):
        def exist(self, board, word):
            """
            :type board: List[List[str]]
            :type word: str
            :rtype: bool
            """
    
            def dfs(x, y, word):
                if len(word) == 0:
                    return True
                # up
                if x > 0 and board[x - 1][y] == word[0]:
                    tmp = board[x][y]
                    board[x][y] = '#'
                    if dfs(x - 1, y, word[1:]):
                        return True
                    board[x][y] = tmp
    
                # down
                if x < len(board) - 1 and board[x + 1][y] == word[0]:
                    tmp = board[x][y]
                    board[x][y] = '#'
                    if dfs(x + 1, y, word[1:]):
                        return True
                    board[x][y] = tmp
    
                # left
                if y > 0 and board[x][y - 1] == word[0]:
                    tmp = board[x][y]
                    board[x][y] = '#'
                    if dfs(x, y - 1, word[1:]):
                        return True
                    board[x][y] = tmp
    
                # right
                if y < len(board[0]) - 1 and board[x][y + 1] == word[0]:
                    tmp = board[x][y]
                    board[x][y] = '#'
                    if dfs(x, y + 1, word[1:]):
                        return True
                    board[x][y] = tmp
    
                return False
    
            for i in range(len(board)):
                for j in range(len(board[0])):
                    if board[i][j] == word[0]:
                        if (dfs(i, j, word[1:])):
                            return True
            return False
    
  • 相关阅读:
    Linux环境变量文件
    Hadoop的ERROR: Attempting to operate on yarn resourcemanager as root的解决方法
    如何启用WSS3.0的匿名访问?
    Microsoft Windows SharePoint Services 3.0
    在sps页面中在新窗口打开文档
    wss3.0安装时的bug
    使用GROUP BY子句的规则
    8种Nosql数据库系统对比
    django学习
    Python socket编程
  • 原文地址:https://www.cnblogs.com/slurm/p/5160204.html
Copyright © 2011-2022 走看看