79 單詞搜尋

2021-09-22 18:28:50 字數 1651 閱讀 3865

)# 不允許重複使用字母

seen =[[

0for i in

range

(n)]

for j in

range

(m)]

for i in

range

(m):

for j in

range

(n):

if self.search(board, word,

0, i, j, seen)

:return

true

return

false

# word[index:] 與 board[x][y]開頭的所有情況 是否匹配?

defsearch

(self, board, word, index, x, y, seen)

:# 座標變換方式 上 右 下 左

d =[(

-1,0

),(0

,1),

(1,0

),(0

,-1)

]# 當前search的是word最後乙個字元

if index ==

len(word)-1

:return board[x]

[y]== word[index]

# 當前search的不是word最後乙個字元

# 若匹配 須遞迴檢視後面的字元是否匹配

# 若不匹配 返回false

if board[x]

[y]== word[index]

:

seen[x]

[y]=

1for i in

range(4

):x_ = x + d[i][0

] y_ = y + d[i][1

]if0<= x_ <= self.lx and

0<= y_ <= self.ly and

not seen[x_]

[y_]

and self.search(board, word, index+

1, x_, y_, seen)

:return

true

# 上右下左 遞迴完之後沒有匹配的單詞 還原seen

seen[x]

[y]=

0# word[index:] 與 board[x][y]開頭的所有情況 不匹配

return

false

79 單詞搜尋

給定乙個二維網格和乙個單詞,找出該單詞是否存在於網格中。單詞必須按照字母順序,通過相鄰的單元格內的字母構成,其中 相鄰 單元格是那些水平相鄰或垂直相鄰的單元格。同乙個單元格內的字母不允許被重複使用。示例 board a b c e s f c s a d e e 給定 word abcced 返回t...

79 單詞搜尋

給定乙個二維網格和乙個單詞,找出該單詞是否存在於網格中。單詞必須按照字母順序,通過相鄰的單元格內的字母構成,其中 相鄰 單元格是那些水平相鄰或垂直相鄰的單元格。同乙個單元格內的字母不允許被重複使用。示例 board a b c e s f c s a d e e 給定 word abcced 返回 ...

79 單詞搜尋

給定乙個二維網格和乙個單詞,找出該單詞是否存在於網格中。單詞必須按照字母順序,通過相鄰的單元格內的字母構成,其中 相鄰 單元格是那些水平相鄰或垂直相鄰的單元格。同乙個單元格內的字母不允許被重複使用。示例 board a b c e s f c s a d e e 給定 word abcced 返回 ...