@@ -65,3 +65,73 @@ def dfs(i, j, str_index):
6565
6666 # ๋ชจ๋ ์๋๋ฅผ ํด๋ ๋ชป ์ฐพ์ผ๋ฉด False
6767 return False
68+
69+
70+ # 7๊ธฐ ํ์ด
71+ # ์๊ฐ ๋ณต์ก๋: O((n * m) * 4 ^ d)
72+ # - depth์ ๊ธธ์ด(d)๋งํผ ๋ค ๋ฐฉํฅ์ ํ์ํ๋ฉฐ, ์ถ๋ฐ์ ์ ๊ฐ์ n * m ๋ชจ๋ ํ์ํ ๋ ์ต์
์ ์๊ฐ
73+ # ๊ณต๊ฐ ๋ณต์ก๋: O(n * m)
74+ # - visited ๋ณ์๋ฅผ ์ฌ์ฉํ๊ธฐ ๋๋ฌธ์ ํ * ์ด์ ๊ฐ์๋งํผ์ ๊ณต๊ฐ์ ํ์๋ก ํจ
75+ class Solution :
76+ def exist (self , board : List [List [str ]], word : str ) -> bool :
77+ # ๋ณด๋์ ํ, ์ด์ ๊ธธ์ด๋ฅผ ๋ฏธ๋ฆฌ ์ ์ฅ
78+ num_rows = len (board )
79+ num_cols = len (board [0 ])
80+
81+ # dfs ํ์ ์ ์ด๋ฏธ ๋ฐฉ๋ฌธํ ๊ฒฝ์ฐ๋ฅผ ์ฒดํฌํ๊ธฐ ์ํ visited๋ฅผ ์์ฑ
82+ visited = [[0 for _ in range (num_cols )] for _ in range (num_rows )]
83+
84+ # dfs ํ์ ์ ํ ์นธ์ ๊ธฐ์ค์ผ๋ก ํ์ฌ 4๋ฐฉํฅ์ผ๋ก ํ์ ๊ฐ๋ฅํ๊ฒ directions์ ๋ง๋ ๋ค.
85+ # ์์๋๋ก ์๋๋ก ์ง์ถ, ์๋ก ์ง์ถ, ์ผ์ชฝ์ผ๋ก ์ง์ถ, ์ค๋ฅธ์ชฝ์ผ๋ก ์ง์ถ
86+ directions = [(0 , 1 ), (0 , - 1 ), (- 1 , 0 ), (1 , 0 )]
87+
88+ def check_exist_word (i , j , depth ):
89+ if depth == len (word ) - 1 :
90+ # depth๊ฐ word์ ๊ธธ์ด์ ๊ฐ๊น์์ง๋ฉด(๋ฐฐ์ด์ด๋ผ -1 ํด์ค)
91+ # ํ์์ ๋ง์ณค์ผ๋ฏ๋ก True๋ฅผ ๋ฐํ
92+ return True
93+
94+ # ํ์ฌ์ ์นธ์ ๋ฐฉ๋ฌธํ๋ค๋ ์๋ฏธ๋ก 1๋ก ๋ณ๊ฒฝ
95+ visited [i ][j ] = 1
96+ for dir_i , dir_j in directions :
97+ # ๋ค ๋ฐฉํฅ์ ์์ฐจ๋ก ํ์ํ๋ค.
98+ # ๋ค์ ์นธ์ ์์น๋ฅผ ๋ํ๋ด๋ next_i์ next_j๋ฅผ ๋จผ์ ๊ณ์ฐ
99+ next_i , next_j = i + dir_i , j + dir_j
100+ if not (
101+ 0 <= next_i < num_rows # ๋ค์ ์นธ์ ํ ๋ฒํธ๊ฐ ํ์ ๊ธธ์ด ๋ด์ ์๊ณ
102+ and 0 <= next_j < num_cols # ๋ค์ ์นธ์ ์ด ๋ฒํธ๊ฐ ์ด์ ๊ธธ์ด ๋ด์ ์๊ณ
103+ and not visited [next_i ][next_j ] # ์์ง ๋ฐฉ๋ฌธํ์ง ์์์ผ๋ฉฐ
104+ and board [next_i ][next_j ] == word [depth + 1 ] # ๋ค์ ๊ธ์๊ฐ word์ ๋ค์ ๊ธ์์ ํด๋นํด์ผ ํจ
105+ ):
106+ # ๊ทธ๋ ์ง ์์ ๊ฒฝ์ฐ์๋ ํ์ํ ํ์๊ฐ ์์ผ๋ฏ๋ก ๋ค์ ๋ฐฉํฅ์ ์ฐพ๋๋ค
107+ continue
108+
109+ # ์์ ์กฐ๊ฑด์ ๋ชจ๋ ๋ง์กฑํ๋ฉด ํ์ํด๋ ๋๋ค.
110+ exist_word = check_exist_word (
111+ next_i ,
112+ next_j ,
113+ depth + 1 # word์ ๋ค์ index๋ฅผ ์ฐพ์์ผ ํจ
114+ )
115+ if exist_word :
116+ # ๋จ์ด๋ฅผ ์ฐพ์๋ค๊ณ ํ๋ฉด early return
117+ return True
118+
119+ # ๋ฐฑํธ๋ํน์ ์ํด ํ์ฌ ์นธ์ visited ๊ฐ์ ์๋ณตํ๋ค.
120+ visited [i ][j ] = 0
121+
122+ # ๋จ์ด๋ฅผ ์ฐพ์ง ๋ชปํ์ ๋ False ๋ฐํ
123+ return False
124+
125+ for i in range (num_rows ):
126+ for j in range (num_cols ):
127+ if board [i ][j ] != word [0 ]:
128+ # ์ถ๋ฐ ๊ธ์๊ฐ word์ ์ฒซ ๊ธ์๋ ๊ฐ์ง ์์ผ๋ฉด ํ์ํ ํ์๊ฐ ์์ผ๋ฏ๋ก ๋๊ธด๋ค.
129+ continue
130+
131+ exist_word = check_exist_word (i , j , 0 )
132+ if exist_word :
133+ # ๋จ์ด๋ฅผ ์ฐพ์์ผ๋ฉด ํ์์ ๋์ด์ ํ์ง ์์๋ ๋๋ฏ๋ก early return
134+ return True
135+
136+ # ๋ณด๋์ ๋ชจ๋ ํ์์ ํด๋ ์ฐพ์ง ๋ชปํ ๊ฒฝ์ฐ์๋ False ๋ฐํ
137+ return False
0 commit comments