题目
给定一个 m x n 二维字符网格 board 和一个单词(字符串)列表 words,找出所有同时在二维网格和字典中出现的单词。
单词必须按照字母顺序,通过 相邻的单元格 内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。
示例
示例1
输入:board = [[“o”,“a”,“a”,“n”],[“e”,“t”,“a”,“e”],[“i”,“h”,“k”,“r”],[“i”,“f”,“l”,“v”]], words = [“oath”,“pea”,“eat”,“rain”]
输出: [“eat”,“oath”]
示例2
输入:board = [[“a”,“b”],[“c”,“d”]], words = [“abcb”]
输出:[]
代码实现
class Solution(object):
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
result = []
for word in words: # "oath" in [...]
for i in range(len(board)): # "["o","a","a","n"]" in [...]
for j, c in enumerate(board[i]): # j:index, c:character
if c == word[0]:
row,column = i,j
for k in range(1,len(word)): # 'o' in "oath"
if row!=0 and board[row-1][column]==word[k]: # up
row = row-1
elif row != len(board)-1 and board[row+1][column]==word[k]: # down
row = row+1
elif column != 0 and board[row][column-1]==word[k]: # left
column = column-1
elif column != len(board)-1 and board[row][column+1]==word[k]: # right
column = column+1
else:
break
if k == len(word)-1:
result.append(word)
return result
if __name__ == "__main__":
board = input()
words = input()
obj = Solution()
result = obj.findWords(board, words)
print(result)
运行结果
[“eat”,“oath”]
[]