zoukankan      html  css  js  c++  java
  • Leetcode 79. Word Search

    https://leetcode.com/problems/word-search/

    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.

    Example:

    board =
    [
      ['A','B','C','E'],
      ['S','F','C','S'],
      ['A','D','E','E']
    ]
    
    Given word = "ABCCED", return true.
    Given word = "SEE", return true.
    Given word = "ABCB", return false.

    • 经典回溯。注意Python列表初始化,复习DFS模版。
     1 class Solution:
     2     def exist(self, board: List[List[str]], word: str) -> bool:
     3         if not word:
     4             return False
     5         
     6         visited = [ [ False for j in range( len( board[ 0 ] ) ) ] for i in range( len( board ) ) ] # remember the way
     7         
     8         def helper(x, y, current):
     9             if current == len( word ):
    10                 return True
    11             
    12             if x < 0 or x >= len( board ) or y < 0 or y >= len( board[ 0 ] ) or visited[x][y] or board[x][y] != word[current]:
    13                 return False
    14             
    15             visited[x][y] = True
    16             
    17             result = (helper(x - 1, y, current + 1) 
    18                     or helper(x + 1, y, current + 1) 
    19                     or helper(x, y - 1, current + 1) 
    20                     or helper(x, y + 1, current + 1) )
    21             
    22             visited[x][y] = False
    23             
    24             return result
    25         
    26         for i in range( len( board ) ):
    27             for j in range( len ( board[ 0 ] ) ):
    28                 if helper(i, j, 0):
    29                     return True
    30         
    31         return False
    View Python Code
  • 相关阅读:
    HTML 网页创建
    CSS3 opacity
    两数相加的和
    九九乘法表
    Linux下的Makefile初入
    linux 下定义寄存器宏 实现类似于STM32的寄存器操作
    Linux 编译与交叉编译
    linux IMX6 汇编点亮一个LED灯
    Linux基本指令与作用
    C# Task 源代码阅读(2)
  • 原文地址:https://www.cnblogs.com/pegasus923/p/11348895.html
Copyright © 2011-2022 走看看