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 special positions in a binary matrix using Python
Suppose we have a binary matrix of order m x n, we have to find the number of special positions in the matrix. A position (i,j) is a special position when mat[i][j] = 1 and all other elements in row i and column j are 0.
So, if the input is like ?
| 1 | 0 | 0 | 0 | 0 |
| 0 | 0 | 1 | 0 | 0 |
| 0 | 0 | 0 | 1 | 1 |
| 0 | 1 | 0 | 0 | 0 |
Then the output will be 3, here the special positions are (0, 0), (1, 2) and (3, 1).
Algorithm
To solve this, we will follow these steps −
Initialize
special = 0-
For each row i in the matrix, do
-
If number of 1s in row
matrix[i]is exactly 1, thenFind the column index where 1 is located
Check if this column has exactly one 1 (at current row)
If yes, increment
specialcounter
-
Return
special
Example
Let us see the following implementation to get better understanding −
def solve(matrix):
special = 0
for i in range(len(matrix)):
if matrix[i].count(1) == 1:
numOfOne = 0
indexOfOne = matrix[i].index(1)
for j in range(len(matrix)):
if matrix[j][indexOfOne] == 1:
numOfOne += 1
if numOfOne > 1:
break
if numOfOne == 1:
special += 1
return special
matrix = [[1,0,0,0,0],
[0,0,1,0,0],
[0,0,0,1,1],
[0,1,0,0,0]]
print(solve(matrix))
3
How It Works
The algorithm works by checking each row for exactly one occurrence of 1. When found, it verifies that the corresponding column also has exactly one occurrence of 1 at the same position. Position (2,3) is not special because row 2 has two 1s, and position (2,4) fails because column 4 would need to be checked but row 2 already disqualifies it.
Optimized Approach
We can optimize by pre-calculating row and column sums ?
def solve_optimized(matrix):
rows = len(matrix)
cols = len(matrix[0])
# Calculate row sums and column sums
row_sums = [sum(matrix[i]) for i in range(rows)]
col_sums = [sum(matrix[i][j] for i in range(rows)) for j in range(cols)]
special = 0
for i in range(rows):
for j in range(cols):
if matrix[i][j] == 1 and row_sums[i] == 1 and col_sums[j] == 1:
special += 1
return special
matrix = [[1,0,0,0,0],
[0,0,1,0,0],
[0,0,0,1,1],
[0,1,0,0,0]]
print(solve_optimized(matrix))
3
Conclusion
A special position in a binary matrix requires exactly one 1 in both its row and column. The optimized approach using pre-calculated sums is more efficient for larger matrices with O(m×n) complexity.
