From a7f5724d7148cdf785973ca247cf461a91633848 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 16 Jul 2022 14:31:55 +0000 Subject: [PATCH] problems: add max area of island --- problems/max-area-of-island.kt | 39 ++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 problems/max-area-of-island.kt diff --git a/problems/max-area-of-island.kt b/problems/max-area-of-island.kt new file mode 100644 index 0000000..64d7edd --- /dev/null +++ b/problems/max-area-of-island.kt @@ -0,0 +1,39 @@ +fun product(xs: Sequence, ys: Sequence): Sequence> = + xs.flatMap { x -> ys.map { y -> x to y } } + +fun product(xs: Iterable, ys: Iterable): Sequence> = + product(xs.asSequence(), ys.asSequence()) + +class Solution { + fun BFS(grid: Array, coords: Pair): Int { + val queue = ArrayDeque>() + 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): Int = + product(grid.indices, grid.first().indices).map { BFS(grid, it) }.max() ?: 0 +}