
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 −
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
- Related Articles
- Python Program to find out the determinant of a given special matrix
- Write Python program to find duplicate rows in a binary matrix
- Program to find longest distance of 1s in binary form of a number using Python
- Program to count number of square submatrices in given binary matrix in Python
- Program to find out the number of special numbers in a given range in Python
- Program to find number of only child in a binary tree in python
- Program to count number of operations to convert binary matrix to zero matrix in C++
- Java Program to Find Cube Root of a number using Binary Search
- Java Program to find Square Root of a number using Binary Search
- Program to find nth smallest number from a given matrix in Python
- Program to find number of distinct island shapes from a given matrix in Python
- Find row number of a binary matrix having maximum number of 1s in C++
- Program to find number of sublists with sum k in a binary list in Python
- C++ Program to Find the Number of occurrences of a given Number using Binary Search approach
- Find maximum path length in a binary matrix in Python
