Last active
September 20, 2021 13:03
-
-
Save zeptometer/ebd41b794c5fa84fd8cf12c0bbdde46a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun toMap(flags: Int): Array<BooleanArray> { | |
return Array(4) { x -> | |
BooleanArray(4) { y -> | |
(flags shr (x * 4 + y)) and 1 == 1 | |
} | |
} | |
} | |
fun isValidMoat(moat: Array<BooleanArray>): Boolean { | |
fun getInitPos(moat: Array<BooleanArray>): Pair<Int, Int> { | |
for (x in 0 until 4) for (y in 0 until 4) | |
if (moat[x][y]) return Pair(x, y); | |
throw RuntimeException() | |
} | |
fun getNeighbors(x: Int, y: Int): List<Pair<Int, Int>> { | |
return listOf( | |
Pair(x - 1, y), | |
Pair(x + 1, y), | |
Pair(x, y + 1), | |
Pair(x, y - 1) | |
).filter { (x, y) -> x in 0..3 && y in 0..3 } | |
} | |
fun hasIsolatedMoat(moat: Array<BooleanArray>, visited: Array<BooleanArray>): Boolean { | |
for (x in 0 until 4) for (y in 0 until 4) | |
if (moat[y][x] && ! visited[y][x]) | |
return true | |
return false | |
} | |
val visited = Array(4) { BooleanArray(4) { false } } | |
val stack = ArrayDeque<Pair<Int, Int>>(); | |
stack.addFirst(getInitPos(moat)); | |
while(! stack.isEmpty()) { | |
val (x, y) = stack.removeFirst(); | |
visited[y][x] = true; | |
for ((nx, ny) in getNeighbors(x, y)) { | |
if (visited[ny][nx]) continue | |
stack.addFirst(Pair(x, y)) | |
} | |
} | |
return hasIsolatedMoat(moat, visited); | |
} | |
fun moatContainsAllVillages( | |
moat: Array<BooleanArray>, | |
villages: Array<BooleanArray> | |
): Boolean { | |
for (x in 0 until 4) for (y in 0 until 4) | |
if (! moat[y][x] && villages[y][x]) | |
return true; | |
return false; | |
} | |
fun main() { | |
val villages = (1 .. 4).map { | |
readLine()!!.split(" ") | |
.map { it.toInt() > 0 } | |
.toBooleanArray() | |
}.toTypedArray() | |
var answer = 0; | |
for (currentFlags in 1 until (1 shl 16)) { | |
val moat = toMap(currentFlags); | |
if (! isValidMoat(moat)) continue; | |
if (! moatContainsAllVillages(moat, villages)) continue; | |
answer++ | |
} | |
println(answer) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment