-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordSearch.kt
More file actions
46 lines (41 loc) · 1.33 KB
/
WordSearch.kt
File metadata and controls
46 lines (41 loc) · 1.33 KB
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
46
package leetcode
/**
* Problem description on [LeetCode](https://leetcode.com/problems/word-search/)
*/
class WordSearch {
fun exist(board: Array<CharArray>, word: String): Boolean {
val used = Array(board.size) {
BooleanArray(board[0].size)
}
for (row in board.indices) {
for (col in board[row].indices) {
val found = search(board, word, used, 0, row, col)
if (found) return true
}
}
return false
}
private fun search(
board: Array<CharArray>,
word: String,
used: Array<BooleanArray>,
from: Int,
row: Int,
col: Int
): Boolean {
if (from > word.lastIndex) return true
if (row < 0 || row > board.lastIndex || col < 0 || col > board[0].lastIndex) return false
if (used[row][col]) return false
var found = false
if (word[from] == board[row][col]) {
used[row][col] = true
found =
search(board, word, used, from + 1, row - 1, col) ||
search(board, word, used, from + 1, row + 1, col) ||
search(board, word, used, from + 1, row, col - 1) ||
search(board, word, used, from + 1, row, col + 1)
used[row][col] = false
}
return found
}
}