1+ """
2+ Word Search II
3+
4+ Given a 2D board and a list of words from the dictionary, find all words in the board.
5+
6+ Each word must be constructed from letters of sequentially adjacent cell, where "adjacent"
7+ cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
8+
9+ For example,
10+ Given words = ["oath","pea","eat","rain"] and board =
11+
12+ [
13+ ['o','a','a','n'],
14+ ['e','t','a','e'],
15+ ['i','h','k','r'],
16+ ['i','f','l','v']
17+ ]
18+ Return ["eat","oath"].
19+ Note:
20+ You may assume that all inputs are consist of lowercase letters a-z.
21+ """
22+
23+ # 太慢, 被拒了
24+ class Solution (object ):
25+ def isExists (self , board , word , y , x , location ):
26+ if len (word ) > len (board ) * len (board [0 ]):
27+ return False
28+ if location == len (word ):
29+ return True
30+ if y < 0 or x < 0 or y == len (board ) or x == len (board [y ]):
31+ return False
32+
33+ if board [y ][x ] != word [location ]:
34+ return False
35+ a = ord ('#' )
36+ board [y ][x ], a = a , board [y ][x ]
37+ ret = self .isExists (board , word , y + 1 , x , location + 1 ) \
38+ or self .isExists (board , word , y - 1 , x , location + 1 ) \
39+ or self .isExists (board , word , y , x + 1 , location + 1 ) \
40+ or self .isExists (board ,word , y , x - 1 , location + 1 )
41+ board [y ][x ], a = a , board [y ][x ]
42+ return ret
43+ def findWords (self , board , words ):
44+ """
45+ :type board: List[List[str]]
46+ :type words: List[str]
47+ :rtype: List[str]
48+ """
49+ if not words :
50+ return []
51+ if not board :
52+ return []
53+ results = []
54+ wordDict = {}
55+ for word in words :
56+ if word in wordDict :
57+ continue
58+
59+ wordDict [word ] = 0
60+
61+ for y in range (len (board )):
62+ if wordDict [word ] > 0 :
63+ continue
64+ for x in range (len (board [0 ])):
65+ if wordDict [word ] > 0 :
66+ continue
67+ if self .isExists (board , word , y , x , 0 ):
68+ wordDict [word ] += 1
69+ results .append (word )
70+ if len (results ) == len (words ):
71+ return results
72+ return results
73+
74+
75+ board = [
76+ ['a' ],
77+ ['a' ]
78+ ]
79+ words = ["a" ]
80+
81+ s = Solution ()
82+ print (s .findWords (board , words ))
0 commit comments