zoukankan      html  css  js  c++  java
  • leetcode 之 word search

    题目描述
    79. Word Search
    
    •Total Accepted: 85823
    •Total Submissions: 357336
    •Difficulty: Medium
    
    
    
    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. 给定一个数组, 和单词,查找该单词是否在数组中出现。数组中每个字符只能用一次,而且保证字符之间是连续的, 即上下左右查找。
    思考:
    这道题第一想到的就是回溯法了。 就像迷宫问题一样,依次遍历数组中的字符作为起点,开始进行查找,
    每次查找有四个方向, 由于每个字符在一次查找中只能出现一次, 所以使用一个数组来标识。 代码如下: class Solution(object): def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ if len(board) == 0 or len(board[0]) == 0: return False used = [[False for j in range(len(board[0]))] for i in range(len(board))] for i in range(0, len(board)): for j in range(0, len(board[0])): if self.back(board, word, 0, i, j, used): return True return False def back(self, board, word, step, i, j, used): if step == len(word): return True if i < 0 or j < 0 or i >= len(board) or j >= len(board[0])
           or used[i][j] or board[i][j] != word[step]: return False used[i][j] = True res = self.back(board, word, step+1, i+1,j, used)
            or self.back(board, word, step+1, i, j+1, used)
            or self.back(board, word, step+1, i-1,j, used)
            or self.back(board, word, step+1, i, j-1, used) used[i][j] = False return res

      

  • 相关阅读:
    apache安装遇到的问题
    babel+gulp实时转码ES6
    highcharts点击切换,不能自适应宽度
    多行文本溢出
    文件上传
    iscroll最后一个列表项无法显示出来
    curry化函数
    zepto中animate方法的使用注意
    js去除中间空格
    JS实现计算任意一个数的各个位数的和
  • 原文地址:https://www.cnblogs.com/missmzt/p/5786723.html
Copyright © 2011-2022 走看看