Word Search
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.
For example,
Given board =
[ ["ABCE"], ["SFCS"], ["ADEE"] ]word =
"ABCCED"
, -> returns
true
,
word =
"SEE"
, -> returns
true
,
word =
"ABCB"
, -> returns
false
.
分析:
这题题目意思描述的不对。
当borad为[ ["ABCE"], ["SFCS"], ["ADEE"] ] 时,其应该为[ ["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"] ] 。
本题使用DFS来做。
代码:
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
lines = len(board)
rows = len(board[0])
# 先判断board中的字符数是否足够word来访问
if rows * lines < len(word):
return False
# 记录word中第一个字符在board中的位置,将从这些位置开始dfs遍历
existposlst = []
for i, l in enumerate(board):
for j, r in enumerate(l):
if r == word[0]:
existposlst.append([i, j])
# 开始DFS
for pos in existposlst:
if self.dfs(board, rows, lines, word[1:], visistposlst=[pos], curpos=pos):
return True
return False
def dfs(self, board, rows, lines, word, visistposlst, curpos):
"""
:visistposlst: 列表类型,记录当前已经访问过的位置,不可重复访问(注意:集合类型无法hashable list)
:curpos: 如[0, 1], 保存当前访问的位置
:rtype: bool
"""
if word == '':
return True
movedirect = [[-1, 0], [1, 0], [0, -1], [0, 1]] # 上下左右
for direct in movedirect:
newpos = [curpos[0] + direct[0], curpos[1] + direct[1]]
if 0 <= newpos[0] < lines and 0 <= newpos[1] < rows and board[newpos[0]][newpos[1]] == word[0]:
if newpos not in visistposlst:
if self.dfs(board, rows, lines, word[1:], visistposlst + [newpos], newpos):
return True
return False
后记:
本题我的代码效率并不高,但是却又找不到优化的办法。