33# Given an m x n grid of characters board and a string word, return true if word exists in the grid.
44# The word can be constructed from letters of sequentially adjacent cells, where adjacent cells
55# are horizontally or vertically neighboring. The same letter cell may not be used more than once.
6- # 시간에서 아웃.
7- import copy
86from collections import Counter , namedtuple
9- from typing import List , Tuple
10-
11- FourSide = namedtuple ("FourSide" , ["east" , "south" , "north" , "west" ])
7+ from typing import List
128
139
1410class Solution :
@@ -24,13 +20,13 @@ def is_include_number_of_characters(self, a_word, b_word):
2420
2521 return res
2622
27- def exist (self , raw_board : List [List [str ]], word : str ) -> bool :
23+ def exist (self , board : List [List [str ]], word : str ) -> bool :
2824 """
2925 [( A, 0, 0 ), ( B, 0, 1 ), ( C, 1, 0 ), ( D, 1, 1 )]
3026 res = list
3127 - 재귀로 푼다.
3228 - 4방에 없으면 리턴
33- - 한번 사용한 것은 4방 찾을 때 안나오게 제약
29+ - 한번 사용한 것은 판을 변경한다.
3430 1. 시작점을 찾는다.
3531 각 시작점 순서로
3632 2. 4방에 다음을 찾는다.
@@ -39,134 +35,55 @@ def exist(self, raw_board: List[List[str]], word: str) -> bool:
3935 [북, 서, 남, 동]
4036 -> [[]]
4137 3. 될때까지 찾는다.
42- """
43- if not self .is_include_number_of_characters (
44- "" .join (["" .join (row ) for row in raw_board ]), word
45- ):
46- return False
47-
48- res = list ()
49- board = self .get_point_board (raw_board )
50- for row in board :
51- for point in [p for p in row if p [0 ] == word [0 ]]:
52- res .append (point )
53- self .append_next_point (1 , point , res , word , board )
54-
55- if self .get_word (res ) == word :
56- return True
57- else :
58- res = list ()
59-
60- return self .get_word (res ) == word
61-
62- def get_word (self , res ):
63- return "" .join ([ele [0 ] for ele in res ])
64-
65- def append_next_point (
66- self ,
67- next_idx : int ,
68- point : List ,
69- res : List ,
70- word : str ,
71- board : List [List ],
72- ) -> None :
73- if next_idx >= len (word ):
74- return
75-
76- len_original_res = len (res )
77- sides = [s for s in self .get4side (board , point ) if s is not None ]
78- for side in [side for side in sides if side [0 ] == word [next_idx ]]:
79- if side in res :
80- continue
81-
82- res .append (side )
83- self .append_next_point (next_idx + 1 , side , res , word , board )
84-
85- if self .get_word (res ) == word :
86- break
87- else :
88- while len_original_res < len (res ):
89- res .pop ()
90-
91- def get4side (self , board : List [List ], point : List ):
92- north = self .get_point (board , ("" , point [1 ] - 1 , point [2 ] + 0 ))
93- west = self .get_point (board , ("" , point [1 ] + 0 , point [2 ] - 1 ))
94- south = self .get_point (board , ("" , point [1 ] + 1 , point [2 ] + 0 ))
95- east = self .get_point (board , ("" , point [1 ] + 0 , point [2 ] + 1 ))
9638
97- return FourSide (
98- east ,
99- south ,
100- north ,
101- west ,
102- )
10339
104- def get_point ( self , board , point ):
105- if point [ 1 ] < 0 or point [ 2 ] < 0 :
106- return None
40+ 1. 보드 배열의 모든 요소를 순회한다.
41+ 2. word[0]과 board[x][y]요소가 같다면
42+ - 재귀호출
10743
108- result = None
109- try :
110- result = board [point [1 ]][point [2 ]]
111- except IndexError :
112- result = None
44+ - x, y가 보드를 벗어나는지 확인
45+ - word[i]와 board[x][y]가 같은지 확인
46+ - 같다면 방문했다는 표시로 board[x][y]의 . 를 변경.
47+ - board[x-1][y]와 다음 문자로 호출
48+ - board[x+1][y]와 다음 문자로 호출
49+ - board[x][y-1]와 다음 문자로 호출
50+ - board[x][y2+]와 다음 문자로 호출
11351
114- return result
11552
116- def get_point_board ( self , raw_board ):
117- board = [[] for _ in range ( len ( raw_board ))]
118- for row_i , row in enumerate ( raw_board ):
119- for col_i , col in enumerate ( row ):
120- board [ row_i ]. append (( col , row_i , col_i ))
53+ """
54+ if not self . is_include_number_of_characters (
55+ "" . join ([ "" . join ( row ) for row in board ]), word
56+ ):
57+ return False
12158
122- return board
59+ for x , row in enumerate (board ):
60+ for y , col in enumerate (row ):
61+ if col == word [0 ] and self .is_word_exist (x , y , word , board ):
62+ return True
12363
64+ return False
12465
125- def test_get_4_side ():
126- t0 = dict (
127- board = [["A" , "B" ], ["C" , "D" ]],
128- word = "AB" ,
129- output = True ,
130- )
131- s = Solution ()
132- board = s .get_point_board (t0 ["board" ])
133- sides = s .get4side (board , ("A" , 0 , 0 ))
134- assert sides .north is None
135- assert sides .west is None
136- assert sides .south == ("C" , 1 , 0 )
137- assert sides .east == ("B" , 0 , 1 )
66+ def is_word_exist (self , x , y , word , board ):
67+ if x < 0 or x >= len (board ) or y < 0 or y >= len (board [x ]):
68+ return False
13869
139- sides = s .get4side (board , ("D" , 1 , 1 ))
140- assert sides .north == ("B" , 0 , 1 )
141- assert sides .west == ("C" , 1 , 0 )
142- assert sides .south is None
143- assert sides .east is None
70+ if word [0 ] != board [x ][y ]:
71+ return False
14472
73+ if len (word ) == 1 :
74+ return True
14575
146- def test_get_point_board ():
147- t0 = dict (
148- board = [["A" , "B" ], ["C" , "D" ]],
149- word = "AB" ,
150- output = True ,
151- )
152- s = Solution ()
76+ board [x ][y ] = "."
15377
154- board = s .get_point_board (t0 ["board" ])
155- assert board == [[("A" , 0 , 0 ), ("B" , 0 , 1 )], [("C" , 1 , 0 ), ("D" , 1 , 1 )]]
78+ for next_x , next_y in [(x + 1 , y ), (x - 1 , y ), (x , y + 1 ), (x , y - 1 )]:
79+ if self .is_word_exist (next_x , next_y , word [1 :], board ):
80+ return True
15681
82+ board [x ][y ] = word [0 ]
83+ return False
15784
158- def test_get_point ():
159- t0 = dict (
160- board = [["A" , "B" ], ["C" , "D" ], []],
161- word = "AB" ,
162- output = True ,
163- )
164- s = Solution ()
165- board = s .get_point_board (t0 ["board" ])
166- a = s .get_point (board , ("" , 0 , 0 ))
167- assert a == ("A" , 0 , 0 )
168- e = s .get_point (board , ("" , 2 , 2 ))
169- assert e is None
85+ def get_word (self , res ):
86+ return "" .join ([ele [0 ] for ele in res ])
17087
17188
17289def test_simple_exist ():
@@ -192,8 +109,8 @@ def test_simple_exist():
192109 )
193110
194111 s = Solution ()
195- # ts = [t0, t1, t2, t3]
196- ts = [t3 ]
112+ ts = [t0 , t1 , t2 , t3 ]
113+ # ts = [t1 ]
197114 for t in ts :
198115 print (t )
199116 assert s .exist (t ["board" ], t ["word" ]) == t ["output" ]
0 commit comments