79. 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 =
[
['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: DFS
UP = (-1, 0)
DOWN = (1, 0)
LEFT = (0, -1)
RIGHT = (0, 1)
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
if not board:
return False
rows = len(board)
cols = len(board[0])
visited = [[False] * cols for _ in xrange(rows)]
def neighbors(row, col):
for x, y in UP, LEFT, DOWN, RIGHT:
i, j = row + x, col + y
if 0 <= i < rows and 0 <= j < cols:
yield i, j
def dfs(row, col, idx):
if visited[row][col] or board[row][col] != word[idx]:
return False
if idx == len(word) - 1:
return True
visited[row][col] = True
for i, j in neighbors(row, col):
if dfs(i, j, idx + 1):
return True
visited[row][col] = False
return False
for row in xrange(rows):
for col in xrange(cols):
if dfs(row, col, 0):
return True
return False