Skip to content

Commit 52536d7

Browse files
committed
feat: WEEK 04 solution (word-search)
1 parent 2bc1c6e commit 52536d7

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

word-search/tigermint.kt

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
class Solution {
2+
3+
private val dx = intArrayOf(-1, 1, 0, 0)
4+
private val dy = intArrayOf(0, 0, -1, 1)
5+
6+
fun exist(board: Array<CharArray>, word: String): Boolean {
7+
val rows = board.size
8+
val cols = board[0].size
9+
val visited = Array(rows) { BooleanArray(cols) }
10+
11+
val starts = mutableListOf<Pair<Int, Int>>()
12+
for (i in 0 until rows) {
13+
for (j in 0 until cols) {
14+
if (board[i][j] == word[0]) starts.add(i to j)
15+
}
16+
}
17+
18+
if (word.length == 1) return starts.isNotEmpty()
19+
20+
var flag = false
21+
22+
fun dfs(start: Pair<Int, Int>, index: Int) {
23+
if (flag) return
24+
if (index == word.length - 1) {
25+
flag = true
26+
return
27+
}
28+
29+
for (i in 0 until 4) {
30+
val nx = start.first + dx[i]
31+
val ny = start.second + dy[i]
32+
33+
if (nx < 0 || nx >= rows) continue
34+
if (ny < 0 || ny >= cols) continue
35+
if (visited[nx][ny]) continue
36+
if (word[index + 1] != board[nx][ny]) continue
37+
38+
visited[nx][ny] = true
39+
dfs(Pair(nx, ny), index + 1)
40+
visited[nx][ny] = false
41+
}
42+
}
43+
44+
for (start in starts) {
45+
visited[start.first][start.second] = true
46+
dfs(start, 0)
47+
visited[start.first][start.second] = false
48+
if (flag) return true
49+
}
50+
51+
return false
52+
}
53+
}

0 commit comments

Comments
 (0)