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

      

  • 相关阅读:
    meego API
    linux的文件cache导致写文件消耗大量内存
    系统内存不断消耗 导致系统停滞(表面像死机) 但又找不到内存泄漏点
    C常用的LinuxC语言函数库
    GUI
    java 集合类结构图
    接口到底是个什么玩意
    抽象类到底是个什么玩意
    异常
    IO流
  • 原文地址:https://www.cnblogs.com/missmzt/p/5786723.html
Copyright © 2011-2022 走看看