바위타는 두루미
[leetcode]79. Word Search 본문
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
'Study > Algorithm' 카테고리의 다른 글
[leetcode]347. Top K Frequent Elements (0) | 2019.08.10 |
---|---|
[leetcode]75. Sort Colors (0) | 2019.08.10 |
[leetcode]78. Subsets (0) | 2019.08.10 |
[leetcode]46. Permutations (0) | 2019.08.10 |
[leetcode]22. Generate Parentheses (0) | 2019.08.09 |
Comments