diff --git a/problems/1582-special-positions-in-a-binary-matrix/main.rb b/problems/1582-special-positions-in-a-binary-matrix/main.rb new file mode 100644 index 0000000..993ceb8 --- /dev/null +++ b/problems/1582-special-positions-in-a-binary-matrix/main.rb @@ -0,0 +1,25 @@ +# @param {Integer[][]} mat +# @return {Integer} +def num_special(mat) + count = 0 + + mat.each_with_index do |row, i| + row.each_with_index do |cell, j| + count += 1 if cell == 1 && special?(mat, i, j) + end + end + + count +end + +def special?(mat, row_index, column_index) + mat[row_index].each_with_index do |cell, x| + return false if cell == 1 && x != column_index + end + + mat.each_with_index do |row, x| + return false if row[column_index] == 1 && x != row_index + end + + true +end diff --git a/problems/1582-special-positions-in-a-binary-matrix/readme.md b/problems/1582-special-positions-in-a-binary-matrix/readme.md new file mode 100644 index 0000000..4b03081 --- /dev/null +++ b/problems/1582-special-positions-in-a-binary-matrix/readme.md @@ -0,0 +1,6 @@ +# 1582. Special Positions in a Binary Matrix + +Given an m x n binary matrix mat, return the number of special positions in mat. + +A position (`i`, `j`) is called special if `mat[i][j]` == `1` +and all other elements in row `i` and column `j` are `0` (rows and columns are 0-indexed). diff --git a/problems/1582-special-positions-in-a-binary-matrix/test.rb b/problems/1582-special-positions-in-a-binary-matrix/test.rb new file mode 100644 index 0000000..0c883d1 --- /dev/null +++ b/problems/1582-special-positions-in-a-binary-matrix/test.rb @@ -0,0 +1,12 @@ +require_relative 'main' +require 'test/unit' + +class TestNumSpecial < Test::Unit::TestCase + def test_simple + assert_equal(1, num_special([[1, 0, 0], [0, 0, 1], [1, 0, 0]])) + end + + def test_multiple + assert_equal(3, num_special([[1, 0, 0], [0, 1, 0], [0, 0, 1]])) + end +end