forked from Cyberavater/leetcode_practice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
79. Word Search.kt
45 lines (37 loc) · 1.28 KB
/
79. Word Search.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution {
fun exist(board: Array<CharArray>, word: String): Boolean {
val maxI = board.lastIndex
val maxJ = board[0].lastIndex
val paths = hashSetOf<Pair<Int, Int>>()
fun dfs(path: Pair<Int, Int>, letterIndex: Int): Boolean {
if (letterIndex == word.length) {
return true
}
if (path.first < 0
|| path.second < 0
|| path.first > maxI
|| path.second > maxJ
|| path in paths
|| board[path.first][path.second] != word[letterIndex]
) {
return false
}
paths.add(path)
val r = (dfs(Pair(path.first + 1, path.second), letterIndex + 1)
|| dfs(Pair(path.first - 1, path.second), letterIndex + 1)
|| dfs(Pair(path.first, path.second + 1), letterIndex + 1)
|| dfs(Pair(path.first, path.second - 1), letterIndex + 1)
)
paths.remove(path)
return r
}
for (i in board.indices){
for (j in board[0].indices){
if (dfs(Pair(i,j), 0)){
return true
}
}
}
return false
}
}