Thanks to visit codestin.com Credit goes to github.com
We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent e91a275 commit 5cc5751Copy full SHA for 5cc5751
79-Word-Search.py
@@ -0,0 +1,25 @@
1
+class Solution:
2
+ def exist(self, board: List[List[str]], word: str) -> bool:
3
+ ROWS, COLS = len(board), len(board[0])
4
+ path = set()
5
+
6
+ def dfs(r, c, i):
7
+ if i == len(word):
8
+ return True
9
+ if (min(r, c) < 0 or r >= ROWS or c >= COLS or
10
+ word[i] != board[r][c] or (r, c) in path):
11
+ return False
12
+ path.add((r, c))
13
+ res = (dfs(r + 1, c, i + 1) or
14
+ dfs(r - 1, c, i + 1) or
15
+ dfs(r, c + 1, i + 1) or
16
+ dfs(r, c - 1, i + 1))
17
+ path.remove((r, c))
18
+ return res
19
20
+ for r in range(ROWS):
21
+ for c in range(COLS):
22
+ if dfs(r, c, 0): return True
23
24
25
+ # O(n * m * 4^n)
0 commit comments