- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

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

3

- Related Questions & Answers
- Program to find valid matrix given row and column sums in Python
- Find sum of all elements in a matrix except the elements in row and-or column of given cell in Python
- How to find the variance of row elements of a matrix in R?
- How to find the row and column index for upper triangular matrix elements in R?
- C++ program to find the Sum of each Row and each Column of a Matrix
- Program to find smallest intersecting element of each row in a matrix in Python
- Find trace of matrix formed by adding Row-major and Column-major order of same matrix in C++ Program
- Find the column number with largest value for each row in an R matrix.
- To print all elements in sorted order from row and column wise sorted matrix in Python
- Python program to find the redundancy rates for each row of a matrix
- Find row number of a binary matrix having maximum number of 1s in C++
- Program to find maximum sum by flipping each row elements in Python
- Program to find number of special positions in a binary matrix using Python
- Matrix row sum and column sum using C program
- Find trace of matrix formed by adding Row-major and Column-major order of same matrix in C++

Advertisements