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

To solve this, we will follow these steps −

• special := 0

• for i in range 0 to row count of matrix, do

• if number of 1s in row matrix[i] is 1, then

• numOfOne := 0

• indexOfOne := position of 1 in matrix[i]

• for j in range 0 to column size of matrix, do

• if matrix[j, indexOfOne] is same as 1, then

• numOfOne := numOfOne + 1

• if numOfOne > 1, then

• come out from the loop

• if numOfOne is same as 1, then

• special := special + 1

• return special

## Example (Python)

Let us see the following implementation to get better understanding −

Live Demo

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

## Input

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

## Output

3