Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find number of elements in matrix follows row column criteria in Python
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.
In simple terms, we need to find cells that contain 1 and are the only 1 in both their row and column.
Example Input
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.
Algorithm
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
Implementation
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))
The output of the above code is ?
3
How It Works
The algorithm works by first calculating the sum of each row and column. If a cell contains 1 and both its row sum and column sum equal 1, it means that cell is the only 1 in both its row and column, satisfying our criteria.
# Example with detailed steps
def solve_detailed(matrix):
if not matrix:
return 0
# Calculate row sums
row = [sum(r) for r in matrix]
print("Row sums:", row)
# Calculate column sums
col = [sum(c) for c in zip(*matrix)]
print("Column sums:", col)
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:
print(f"Found valid cell at ({r},{c})")
res += 1
return res
matrix = [
[0, 0, 1],
[1, 0, 0],
[0, 1, 0]
]
print("Result:", solve_detailed(matrix))
Row sums: [1, 1, 1] Column sums: [1, 1, 1] Found valid cell at (0,2) Found valid cell at (1,0) Found valid cell at (2,1) Result: 3
Conclusion
This solution efficiently finds matrix elements that are the only 1 in both their row and column by pre-computing row and column sums. The time complexity is O(m×n) where m and n are the matrix dimensions.
