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:
parent
8991ba7ff1
commit
d1d9ad0c74
1 changed files with 26 additions and 0 deletions
26
kt/count-square-submatrices-with-all-ones.kt
Normal file
26
kt/count-square-submatrices-with-all-ones.kt
Normal 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
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue