zoukankan      html  css  js  c++  java
  • 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,看能否找到单词,遇到不符合的情况则回退,不再向下进行。因为题目要求同一个字母单元不能被重复使用,所以需要维护一个visited矩阵,将此次DFS过程中用到的点都置为True。当处理完一次路径,需要将该路径经过的所有结点的visited都置为False。一遍别的路径使用。代码如下:

    class Solution(object):
        def exist(self, board, word):
            """
            :type board: List[List[str]]
            :type word: str
            :rtype: bool
            """
            if not board and word:
                return False
            if not board and not word:
                return True
            visited = [[False] * len(board[0]) for i in xrange(len(board))]
            for i in xrange(len(board)):
                for j in xrange(len(board[0])):
                    if  self.search(board, visited, word, 0, i, j):
                        return True
            return False
            
        def search(self, board, visited, word, i, x, y):
            if i == len(word):
                return True
            if x < 0 or y < 0 or x >= len(board) or y >= len(board[0]) or visited[x][y] or word[i] != board[x][y]: #越界,已访问,不等于原有单词这三种情况不进行处理.
                return False
            visited[x][y] = True
            res = self.search(board, visited, word, i+1, x+1, y) or 
                  self.search(board, visited, word, i+1, x, y+1) or 
                  self.search(board, visited, word, i+1, x-1, y) or 
                  self.search(board, visited, word, i+1, x, y-1)
            visited[x][y] = False
            return res

    这题最坏一共进行O(m*n)次遍历。每次DFS的顶点数为m*n,边数也为m*n,总的时间复杂度为O(m*n) (O(V+E). 所以时间复杂度最坏是O(m^2*n^2).空间复杂度是栈的高度和visited矩阵中的比较大的值。O(m*n).栈高度最高也是O(m*n)级别的。

  • 相关阅读:
    numpy计算路线距离
    WebApi安全性 使用TOKEN+签名验证
    从SQL查询分析器中读取EXCEL中的内容
    Autofac应用总结
    Visual Studio提示“无法启动IIS Express Web服务器”的解决方法
    架构 : 三层架构、MVC、MVP、MVVM
    Asp.Net MVC :路由器
    myeclipse10安装egit和使用
    myeclipse10.7安装git插件
    SQLite之C#连接SQLite
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5641718.html
Copyright © 2011-2022 走看看