Problem 1582: Special positions in a binary matrix

This commit is contained in:
Ivan R. 2023-03-13 21:37:25 +05:00
parent 7b00ab2429
commit ee78ba4a9b
No known key found for this signature in database
GPG key ID: 56C7BAAE859B302C
3 changed files with 43 additions and 0 deletions

View file

@ -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

View file

@ -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).

View file

@ -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