All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g1501_1600.s1504_count_submatrices_with_all_ones.Solution.kt Maven / Gradle / Ivy

There is a newer version: 1.32
Show newest version
package g1501_1600.s1504_count_submatrices_with_all_ones

// #Medium #Array #Dynamic_Programming #Matrix #Stack #Monotonic_Stack
// #2023_06_12_Time_265_ms_(80.00%)_Space_44.6_MB_(80.00%)

class Solution {
    fun numSubmat(mat: Array): Int {
        val dp = Array(mat.size) { IntArray(mat[0].size) }
        for (i in mat.indices) {
            var c = 0
            for (j in mat[0].indices.reversed()) {
                if (mat[i][j] == 1) {
                    c++
                } else {
                    c = 0
                }
                dp[i][j] = c
            }
        }
        var ans = 0
        for (i in mat.indices) {
            for (j in mat[0].indices) {
                var x = Int.MAX_VALUE
                for (k in i until mat.size) {
                    x = Math.min(x, dp[k][j])
                    ans += x
                }
            }
        }
        return ans
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy