# Program to find number of elements in matrix follows row column criteria in Python

PythonServer Side ProgrammingProgramming

Suppose we have a binary matrix; we have to find the number of elements in matrix that follows the following rules −

• matrix[r, c] = 1

• matrix[r, j] = 0 for every j when j is not equal to c and matrix[i, c] = 0 for every i when i is not equal to r.

So, if the input is like

 0 0 1 1 0 0 0 1 0

then the output will be 3, because we have cells (0,2), (1,0) and (2,1) those meet the criteria.

To solve this, we will follow these steps −

• if matrix is empty, then

• return 0

• row := a list of sum of all row entries in matrix

• col := a list of sum of all column entries in matrix

• m := row count of matrix

• n := column count of matrix

• res := 0

• for r in range 0 to m - 1, do

• for c in range 0 to n - 1, do

• if matrix[r, c] is 1 and row[r] is 1 and col[c] is also 1, then

• res := res + 1

• return res

## Example

Let us see the following implementation to get better understanding

def solve(matrix):
if not matrix:
return 0

row = [sum(r) for r in matrix]
col = [sum(c) for c in zip(*matrix)]

m, n = len(matrix), len(matrix[0])
res = 0
for r in range(m):
for c in range(n):
if matrix[r][c] == 1 and row[r] == 1 and col[c] == 1:
res += 1
return res

matrix = [
[0, 0, 1],
[1, 0, 0],
[0, 1, 0]
]
print(solve(matrix))

## Input

[[0, 0, 1],[1, 0, 0],[0, 1, 0]]


## Output

3
Published on 11-Oct-2021 07:56:54
Advertisements