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 + } +}