Study/Algorithm
[leetcode]79. Word Search
DoRoMii
2019. 8. 10. 11:19
728x90
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.
Example:
board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
class Solution(object):
def dfs(self, board, word, point):
if not word:
return True
direct = [[-1,0,1,0],[0,-1,0,1]]
for i in range(4):
cur_y = point[0]+ direct[0][i]
cur_x = point[1]+ direct[1][i]
if cur_y >=0 and cur_y < len(board) and cur_x >=0 and cur_x < len(board[0]) and board[cur_y][cur_x]== word[0]:
origin = board[cur_y][cur_x]
board[cur_y][cur_x] = '0'
result = self.dfs(board, word[1:], (cur_y, cur_x))
if result :
return True
board[cur_y][cur_x] = origin
return False
def exist(self, board, word):
if len(board) == 0 or len(board[0])== 0:
return False
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == word[0]:
origin = board[i][j]
board[i][j] = '0'
result = self.dfs(board, word[1:], (i,j))
if result:
return True
board[i][j] = origin
return False