Skip to content

Commit f273ad4

Browse files
committed
[Week4](gmlwls96) word search
1 parent 2b38afe commit f273ad4

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

word-search/gmlwls96.kt

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
class Solution {
2+
3+
// 풀이 : dfs
4+
// 시간 :O(m * n * 4^w), 공간 :O(m * n + w)
5+
val movePos = arrayOf(
6+
intArrayOf(-1, 0),
7+
intArrayOf(0, -1),
8+
intArrayOf(1, 0),
9+
intArrayOf(0, 1)
10+
)
11+
12+
fun exist(board: Array<CharArray>, word: String): Boolean {
13+
for (y in board.indices) {
14+
for (x in board[y].indices) {
15+
if (existDfs(
16+
board,
17+
Array(board.size) { BooleanArray(board[it].size) },
18+
word,
19+
"",
20+
y,
21+
x
22+
)
23+
) {
24+
return true
25+
}
26+
}
27+
}
28+
return false
29+
}
30+
31+
private fun existDfs(
32+
board: Array<CharArray>,
33+
visit: Array<BooleanArray>,
34+
findWord: String,
35+
currentWord: String,
36+
y: Int,
37+
x: Int
38+
): Boolean {
39+
if (findWord == currentWord) return true
40+
val findChar = findWord[currentWord.length]
41+
if (board[y][x] == findChar) {
42+
val newWord = currentWord + board[y][x]
43+
visit[y][x] = true
44+
for (pos in movePos) {
45+
val newY = y + pos[0]
46+
val newX = x + pos[1]
47+
if (newY >= 0 && newX >= 0
48+
&& newY < board.size
49+
&& newX < board[newY].size
50+
&& !visit[newY][newX]
51+
&& existDfs(
52+
board = board,
53+
visit = visit,
54+
findWord = findWord,
55+
currentWord = newWord,
56+
y = newY,
57+
x = newX
58+
)
59+
) {
60+
return true
61+
}
62+
}
63+
visit[y][x] = false
64+
}
65+
return false
66+
}
67+
}

0 commit comments

Comments
 (0)