Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8e3e08e

Browse files
1
1 parent 79b65c5 commit 8e3e08e

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

‎src/main/kotlin/p34xx/Problem3459.kt

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package p34xx
2+
3+
import util.expect
4+
import kotlin.math.absoluteValue
5+
6+
fun main() {
7+
class Solution {
8+
fun lenOfVDiagonal(grid: Array<IntArray>): Int {
9+
val directions = arrayOf(
10+
1 to 1,
11+
1 to -1,
12+
-1 to -1,
13+
-1 to 1,
14+
)
15+
16+
val initPos = hashSetOf<Pair<Int, Int>>()
17+
val cache = Array(grid.size) { r ->
18+
Array(grid[r].size) { c ->
19+
if (grid[r][c] == 1) {
20+
initPos.add(r to c)
21+
}
22+
23+
Array(4) { intArrayOf(0, 0) }
24+
}
25+
}
26+
27+
fun dfs(pos: Pair<Int, Int>, directionIndex: Int, turnCount: Int): Int {
28+
return if (cache[pos.first][pos.second][directionIndex][turnCount] > 0) {
29+
cache[pos.first][pos.second][directionIndex][turnCount]
30+
} else {
31+
var result = 0
32+
33+
val currentNum = grid[pos.first][pos.second]
34+
35+
val forwardPos = pos.first + directions[directionIndex].first to pos.second + directions[directionIndex].second
36+
37+
directions[directionIndex].let {
38+
grid.getOrNull(forwardPos.first)?.getOrNull(forwardPos.second)
39+
}?.takeIf {
40+
currentNum == 1 && it == 2 || (currentNum - it).absoluteValue == 2
41+
}?.also {
42+
result = dfs(forwardPos, directionIndex, turnCount)
43+
}
44+
45+
if (turnCount == 1 && currentNum != 1) {
46+
val turnDirectionIndex = (directionIndex + 1) % 4
47+
val turnPos = pos.first + directions[turnDirectionIndex].first to pos.second + directions[turnDirectionIndex].second
48+
grid.getOrNull(turnPos.first)?.getOrNull(turnPos.second)?.takeIf {
49+
it != currentNum && it != 1
50+
}?.also {
51+
result = maxOf(result, dfs(turnPos, turnDirectionIndex, 0))
52+
}
53+
}
54+
55+
result++
56+
cache[pos.first][pos.second][directionIndex][turnCount] = result
57+
result
58+
}
59+
}
60+
61+
return initPos.maxOfOrNull { pos ->
62+
(0 until 4).maxOf { directionIndex ->
63+
maxOf(dfs(pos, directionIndex, 0), dfs(pos, directionIndex, 1))
64+
}
65+
} ?: 0
66+
}
67+
}
68+
69+
expect {
70+
Solution().lenOfVDiagonal(
71+
arrayOf(
72+
intArrayOf(1, 1, 2, 1, 0, 1, 1, 0, 0),
73+
intArrayOf(1, 0, 1, 2, 2, 0, 2, 1, 1),
74+
intArrayOf(1, 0, 2, 0, 2, 1, 1, 1, 1),
75+
)
76+
)
77+
}
78+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /