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)级别的。

  • 相关阅读:
    对计算机科学与技术专业的认识及未来的规划
    秋季学期学习总结
    自我介绍
    Leetcode每日一题 83. 删除排序链表中的重复元素
    Leetcode每日一题 82. 删除排序链表中的重复元素 II
    Leetcode每日一题 456.132 模式
    Leetcode每日一题 341. 扁平化嵌套列表迭代器
    Leetcode每日一题 191. 位1的个数
    Leetcode每日一题 73. 矩阵置零
    Leetcode每日一题 150. 逆波兰表达式求值
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5641718.html
Copyright © 2011-2022 走看看