您的位置:首页 > 其它

LeetCode 79. Word Search

2016-11-03 21:42 302 查看

Problem Statement

(Source) 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 =

[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]


word =
"ABCCED"
, -> returns
true
,

word =
"SEE"
, -> returns
true
,

word =
"ABCB"
, -> returns
false
.

Solution

Tags:
Backtracking
.

class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
return any(self.bt(board, word, [word[0]], set([(x, y)]), x, y) for x in xrange(len(board)) for y in xrange(len(board[0])) if board[x][y] == word[0])

def bt(self, board, word, ass, visited, x, y):
if len(ass) == len(word):
return ''.join(ass) == word
else:
m, n = len(board), len(board[0])
if x - 1 >= 0 and board[x-1][y] == word[len(ass)] and (x-1, y) not in visited:
visited.add((x-1, y))
ass.append(board[x-1][y])
if self.bt(board, word, ass, visited, x-1, y):
return True
else:
ass.pop()
visited.remove((x-1, y))
if x + 1 < m and board[x+1][y] == word[len(ass)] and (x+1, y) not in visited:
visited.add((x+1, y))
ass.append(board[x+1][y])
if self.bt(board, word, ass, visited, x+1, y):
return True
else:
ass.pop()
visited.remove((x+1, y))
if y - 1 >= 0 and board[x][y-1] == word[len(ass)] and (x, y-1) not in visited:
visited.add((x, y-1))
ass.append(board[x][y-1])
if self.bt(board, word, ass, visited, x, y-1):
return True
else:
ass.pop()
visited.remove((x, y-1))
if y + 1 < n and board[x][y+1] == word[len(ass)] and (x, y+1) not in visited:
visited.add((x, y+1))
ass.append(board[x][y+1])
if self.bt(board, word, ass, visited, x, y+1):
return True
else:
ass.pop()
visited.remove((x, y+1))
return False


A more concise solution with the same idea:

class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
return any(self.bt(board, word, [word[0]], set([(x, y)]), x, y) for x in xrange(len(board)) for y in xrange(len(board[0])) if board[x][y] == word[0])

def bt(self, board, word, ass, visited, x, y):
if len(ass) == len(word):
return ''.join(ass) == word
else:
m, n = len(board), len(board[0])
offset = [1, 0, -1, 0, 1]
for index in xrange(4):
xx, yy = x + offset[index], y + offset[index+1]
if 0 <= xx < m and 0 <= yy < n and board[xx][yy] == word[len(ass)] and (xx, yy) not in visited:
visited.add((xx, yy))
ass.append(board[xx][yy])
if self.bt(board, word, ass, visited, xx, yy):
return True
else:
ass.pop()
visited.remove((xx, yy))
return False
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: