# Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix using Python?

PythonServer Side ProgrammingProgramming

In this section we are going to see a python program that counts negative numbers in Row-wise and Column-wise sorted matrix with optimal solution.

Row-wise and column-wise sorted array means, each value at any index is small or equal to the value at the index in next column and next row.

## For example in below matrix M

M = [[-40, -12, 1, 5],
[-20, -2, 5, 15],
[-22, -1, 13, 18],
[-12, 0, 15, 38]]

In above matrix M, the first column of first row is -40, which is smaller than the value at next column value in same row i.e. -12 and is also smaller than the value in next row in the same column i.e. -20 and so on.

## Example 2

# The matrix must be sorted in ascending order. If not, the algorithm will not work properly
matrix = [
[-40, -12, 1, 5],
[-20, -2, 5, 15],
[-22, -1, 13, 18],
[-12, 0, 15, 38]]
# To obtain the number of row
rowCount = len(matrix)
columnCount = 0

# To obtain the number of column
for i in matrix[0]:
columnCount += 1
a = 0
b = 0
count_Of_Negative_Integer = 0
while a < rowCount and b < columnCount:
if matrix[a][b] >= 0:
a += 1
b = 0
else:
count_Of_Negative_Integer += 1
b += 1
print("Count of Negative Integers in sorted Matrix is: ",count_Of_Negative_Integer)

## Result

Count of Negative Integers in sorted Matrix is: 7

In above program,

• >=0: first we try to find the count of negative integer, less than 0.

• Because in above program, we are trying to get negative integers, however, same program can be used to find the count of integer that is less than any particular integers(n). For example to find the count of integer that is less than or equal to 5 using >5.

Updated on 30-Jul-2019 22:30:26