https://leetcode.com/problems/special-positions-in-a-binary-matrix/description/ Easy

Условие

Дана бинарная матрица mat размера m × n. Позиция (i, j) называется особой, если mat[i][j] = 1 и все остальные элементы в i-й строке и j-м столбце равны 0. Требуется вернуть количество таких особых позиций.

Решение

class Solution {
    fun numSpecial(mat: Array<IntArray>): Int {
        val rows = IntArray(mat.size)
        val cols = IntArray(mat[0].size)
        for (i in mat.indices) {
            for (j in mat[0].indices) {
                if (mat[i][j] == 1) {
                    rows[i]++
                    cols[j]++
                }
            }
        }
        var count = 0
        for (i in mat.indices) {
            for (j in mat[0].indices) {
                if (mat[i][j] == 1 && rows[i] == 1 && cols[j] == 1) {
                    count++
                }
            }
        }
        return count
    }
}