From d1d9ad0c747af67896ea4a42dbcf7a848158125c Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 27 Oct 2024 22:54:59 +0100 Subject: [PATCH] =?UTF-8?q?kt:=20add=20=C2=AB1277.=20Count=20Square=20Subm?= =?UTF-8?q?atrices=20with=20All=20Ones=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/count-square-submatrices-with-all-ones/ Signed-off-by: Matej Focko --- kt/count-square-submatrices-with-all-ones.kt | 26 ++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 kt/count-square-submatrices-with-all-ones.kt diff --git a/kt/count-square-submatrices-with-all-ones.kt b/kt/count-square-submatrices-with-all-ones.kt new file mode 100644 index 0000000..8198cd7 --- /dev/null +++ b/kt/count-square-submatrices-with-all-ones.kt @@ -0,0 +1,26 @@ +class Solution { + 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()) + + fun countSquares(matrix: Array): Int { + val (rows, columns) = matrix.size to matrix[0].size + val dp = Array(rows + 1) { IntArray(columns + 1) } + + var answer = 0 + for ((y, x) in product(0.. + matrix[y][x] == 1 + }) { + dp[y + 1][x + 1] = 1 + listOf(dp[y][x + 1], dp[y + 1][x], dp[y][x]).min() + answer += dp[y + 1][x + 1] + } + + return answer + } +}