LeetCode 솔루션 분류
[11/24] 79. Word Search
본문
Medium
12096487Add to ListShareGiven an m x n
grid of characters board
and a string word
, return true
if word
exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example 1:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" Output: true
Example 2:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" Output: true
Example 3:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" Output: false
Constraints:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board
andword
consists of only lowercase and uppercase English letters.
Follow up: Could you use search pruning to make your solution faster with a larger board
?
Accepted
1,173,744
Submissions
2,929,480
태그
#Amazon, #Bloomberg, #Uber, #Karat, #Microsoft, #Cisco, #Google, #TikTok, #Indeed, #Facebook, #Apple, #Walmart Global Tech, #Adobe
관련자료
-
링크
댓글 1
학부유학생님의 댓글
- 익명
- 작성일
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
ROW, COL = len(board), len(board[0])
visited = set()
def dfs(row, col, i):
if (row >= ROW or col >= COL or row < 0 or col < 0 or (row,col) in visited or word[i] != board[row][col]):
return False
visited.add((row,col))
if i == len(word)-1:
return True
ret_val = dfs(row+1, col, i+1) or dfs(row, col+1, i+1) or dfs(row-1,col,i+1) or dfs(row, col-1, i+1)
visited.remove((row,col))
return ret_val
for row in range(ROW):
for col in range(COL):
if dfs(row, col, 0): return True
return False