Problem 1582: Special positions in a binary matrix
This commit is contained in:
parent
7b00ab2429
commit
ee78ba4a9b
3 changed files with 43 additions and 0 deletions
25
problems/1582-special-positions-in-a-binary-matrix/main.rb
Normal file
25
problems/1582-special-positions-in-a-binary-matrix/main.rb
Normal 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
|
|
@ -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).
|
12
problems/1582-special-positions-in-a-binary-matrix/test.rb
Normal file
12
problems/1582-special-positions-in-a-binary-matrix/test.rb
Normal 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
|
Loading…
Reference in a new issue