File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ val _DRCS = listOf (
2
+ listOf (0 , - 1 ),
3
+ listOf (0 , 1 ),
4
+ listOf (- 1 , 0 ),
5
+ listOf (1 , 0 ),
6
+ )
7
+
8
+ class Solution {
9
+ fun exist (board : Array <CharArray >, word : String ): Boolean {
10
+ val offset = ' A' .code
11
+ val invertedIndex = List (' z' .code - offset + 1 ) {mutableListOf<List <Int >>()}
12
+ board.withIndex()
13
+ .forEach { row ->
14
+ row.value
15
+ .withIndex()
16
+ .forEach {
17
+ invertedIndex[it.value.toInt() - offset].add(listOf (row.index, it.index))
18
+ }
19
+ }
20
+ val freq = MutableList (invertedIndex.size) {0 }
21
+ word.map {it.toInt() - offset}
22
+ .forEach {
23
+ freq[it]++
24
+ }
25
+ if ((0 until freq.size).any {freq[it] > invertedIndex[it].size}) {
26
+ return false
27
+ }
28
+ val target = if (invertedIndex[word.first().toInt() - offset].size <= invertedIndex[word.last().toInt() - offset].size) word
29
+ else word.reversed()
30
+ val stack = invertedIndex[target.first().toInt() - offset].map {
31
+ mutableListOf (it.first(), it.last(), 0 , 1 )
32
+ }.toMutableList()
33
+ val visited = MutableList (board.size) {MutableList (board.first().size) {false }}
34
+ while (! stack.isEmpty()) {
35
+ val u = stack.last()
36
+ if (u[2 ] == 4 ) {
37
+ visited[u[0 ]][u[1 ]] = false
38
+ stack.removeLast()
39
+ continue
40
+ }
41
+ if (u[2 ] == 0 ) {
42
+ if (u[3 ] == target.length) {
43
+ return true
44
+ }
45
+ visited[u[0 ]][u[1 ]] = true
46
+ }
47
+ val drc = _DRCS [u[2 ]]
48
+ u[2 ]++
49
+ val v = mutableListOf (u[0 ] + drc[0 ], u[1 ] + drc[1 ], 0 , u[3 ] + 1 )
50
+ if (v[0 ] == - 1 || v[0 ] == board.size || v[1 ] == - 1 || v[1 ] == board.first().size
51
+ || visited[v[0 ]][v[1 ]] || board[v[0 ]][v[1 ]] != target[u[3 ]]) {
52
+ continue
53
+ }
54
+ stack.add(v)
55
+ }
56
+ return false
57
+ }
58
+ }
You can’t perform that action at this time.
0 commit comments