Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c03e56f

Browse files
committed
[20240403] Solve April challenge
1 parent 77ea8ae commit c03e56f

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

‎challenge/2024/04/03_word_search.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# https://leetcode.com/problems/word-search/?envType=daily-question&envId=2024年04月03日
2+
3+
4+
from typing import List
5+
6+
7+
class Solution:
8+
9+
def exist(self, board: List[List[str]], word: str) -> bool:
10+
11+
for i in range(len(board)):
12+
for j in range(len(board[0])):
13+
if self.check(word, 0, i, j, board):
14+
return True
15+
16+
return False
17+
18+
def check(self, word, k, i, j, board):
19+
20+
if i < 0 or i >= len(board):
21+
return False
22+
23+
if j < 0 or j >= len(board[0]):
24+
return False
25+
26+
if k >= len(word):
27+
return False
28+
29+
if word[k] != board[i][j]:
30+
return False
31+
32+
# 여기 왔다는 건 단어를 다 찾았다는 의미이다.
33+
if k == len(word) - 1:
34+
return True
35+
36+
# 이미 확인한 보드를 체크하는 부분
37+
board[i][j] = '#'
38+
39+
# 끝까지 하나라도 갔으면 성공한 것이다.
40+
res = (
41+
self.check(word, k + 1, i + 1, j, board) or
42+
self.check(word, k + 1, i, j + 1, board) or
43+
self.check(word, k + 1, i - 1, j, board) or
44+
self.check(word, k + 1, i, j - 1, board)
45+
)
46+
# backtracing을 대비에 원복함
47+
board[i][j] = word[k]
48+
49+
return res
50+
51+
52+
if __name__ == '__main__':
53+
solution = Solution()
54+
55+
print(solution.exist([["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"]], "ABCCED"))
56+
print(solution.exist([["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"]], "SEE"))
57+
print(solution.exist([["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"]], "ABCB"))
58+
print(solution.exist([["a", "b"], ["c", "d"]], "bacd"))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /