problems: add max area of island
This commit is contained in:
parent
852221b295
commit
a7f5724d71
1 changed files with 39 additions and 0 deletions
39
problems/max-area-of-island.kt
Normal file
39
problems/max-area-of-island.kt
Normal file
|
@ -0,0 +1,39 @@
|
|||
fun <A, B> product(xs: Sequence<A>, ys: Sequence<B>): Sequence<Pair<A, B>> =
|
||||
xs.flatMap { x -> ys.map { y -> x to y } }
|
||||
|
||||
fun <A, B> product(xs: Iterable<A>, ys: Iterable<B>): Sequence<Pair<A, B>> =
|
||||
product(xs.asSequence(), ys.asSequence())
|
||||
|
||||
class Solution {
|
||||
fun BFS(grid: Array<IntArray>, coords: Pair<Int, Int>): Int {
|
||||
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
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
// mark it as done
|
||||
grid[y][x] = 0
|
||||
size++
|
||||
}
|
||||
|
||||
return size
|
||||
}
|
||||
|
||||
fun maxAreaOfIsland(grid: Array<IntArray>): Int =
|
||||
product(grid.indices, grid.first().indices).map { BFS(grid, it) }.max() ?: 0
|
||||
}
|
Loading…
Reference in a new issue