kt: add «1277. Count Square Submatrices with All Ones»

URL:	https://leetcode.com/problems/count-square-submatrices-with-all-ones/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-10-27 22:54:59 +01:00
parent 8991ba7ff1
commit d1d9ad0c74
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,26 @@
class Solution {
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())
fun countSquares(matrix: Array<IntArray>): 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..<rows, 0..<columns).filter { (y, x) ->
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
}
}