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

 

posted on 2019-08-13 21:57  浩然119  阅读(156)  评论(0编辑  收藏  举报