2024-05-17 18:24:05 +02:00
|
|
|
fun <A, B> product(
|
|
|
|
xs: Sequence<A>,
|
|
|
|
ys: Sequence<B>,
|
|
|
|
): Sequence<Pair<A, B>> = xs.flatMap { x -> ys.map { y -> x to y } }
|
2022-07-16 16:31:55 +02:00
|
|
|
|
2024-05-17 18:24:05 +02:00
|
|
|
fun <A, B> product(
|
|
|
|
xs: Iterable<A>,
|
|
|
|
ys: Iterable<B>,
|
|
|
|
): Sequence<Pair<A, B>> = product(xs.asSequence(), ys.asSequence())
|
2022-09-09 18:56:13 +02:00
|
|
|
|
2022-07-16 16:31:55 +02:00
|
|
|
class Solution {
|
2024-05-17 18:24:05 +02:00
|
|
|
fun runBFS(
|
|
|
|
grid: Array<IntArray>,
|
|
|
|
coords: Pair<Int, Int>,
|
|
|
|
): Int {
|
2022-07-16 16:31:55 +02:00
|
|
|
val queue = ArrayDeque<Pair<Int, Int>>()
|
|
|
|
queue.addLast(coords)
|
|
|
|
|
|
|
|
var size = 0
|
|
|
|
while (!queue.isEmpty()) {
|
|
|
|
val (y, x) = queue.removeFirst()
|
|
|
|
if (grid[y][x] != 1) {
|
|
|
|
continue
|
|
|
|
}
|
2022-09-09 18:56:13 +02:00
|
|
|
|
2022-07-16 16:31:55 +02:00
|
|
|
for ((dy, dx) in sequenceOf(0 to 1, 1 to 0, 0 to -1, -1 to 0)) {
|
|
|
|
if (!(y + dy in grid.indices) || !(x + dx in grid[y + dy].indices)) {
|
|
|
|
continue
|
|
|
|
} else if (grid[y + dy][x + dx] != 1) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
queue.addLast(y + dy to x + dx)
|
|
|
|
}
|
2022-09-09 18:56:13 +02:00
|
|
|
|
2022-07-16 16:31:55 +02:00
|
|
|
// mark it as done
|
|
|
|
grid[y][x] = 0
|
|
|
|
size++
|
|
|
|
}
|
2022-09-09 18:56:13 +02:00
|
|
|
|
2022-07-16 16:31:55 +02:00
|
|
|
return size
|
|
|
|
}
|
2022-09-09 18:56:13 +02:00
|
|
|
|
2024-05-17 18:24:05 +02:00
|
|
|
fun maxAreaOfIsland(grid: Array<IntArray>): Int = product(grid.indices, grid.first().indices).map { runBFS(grid, it) }.max() ?: 0
|
2022-07-16 16:31:55 +02:00
|
|
|
}
|