Skip to content

Commit af96ad5

Browse files
committed
Word Search
1 parent 3fa6865 commit af96ad5

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

Backtracking/79-Word-Search.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
'''Leetcode- https://leetcode.com/problems/word-search/'''
2+
'''
3+
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
4+
5+
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.
6+
7+
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
8+
Output: true
9+
'''
10+
11+
# Solution
12+
def exist(board, word):
13+
ROWS, COLS = len(board), len(board[0])
14+
path = set()
15+
16+
def dfs(r, c, i):
17+
if i == len(word):
18+
return True
19+
if (r < 0 or c < 0 or
20+
r >= ROWS or c >= COLS or
21+
word[i] != board[r][c] or
22+
(r, c) in path):
23+
return False
24+
25+
path.add((r, c))
26+
res = (dfs(r+1, c, i+1) or
27+
dfs(r-1, c, i+1) or
28+
dfs(r, c+1, i+1) or
29+
dfs(r, c-1, i+1))
30+
path.remove((r, c))
31+
return res
32+
33+
for r in range(ROWS):
34+
for c in range(COLS):
35+
if dfs(r, c, 0):
36+
return True
37+
return False
38+
39+
#T: O(n*m*4^n)
40+
#S: O(n)

README.md

+4-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,4 @@
1-
# leetcode-solutions-python
1+
# leetcode-solutions-python
2+
3+
- [x] [Backtracking](Backtracking)
4+
- [x] [Word Search](Backtracking/79-Word-Search.py)

0 commit comments

Comments
 (0)