
You are given ‘N’ = 3, ‘M’ = 2 and ‘MAT’= [[3, 1],[2, -1],[1, 2]]. Then the answer will be two for the first test case because there are two negative numbers in the given matrix(-1, -2).
The first line of the input contains a single integer 'T', representing the number of test cases.
The first line of each test case contains two space-separated integers, ‘N’ and ‘M’, representing the number of rows and columns in ‘MAT’, respectively.
The next ‘N’ lines contain ‘M’ space-separated integers representing the elements of ‘MAT’.
For each test case, print the number of negative numbers in ‘MAT’.
Print the output of each test case in a separate line.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 5000
1 <= M <= 5000
-10^6 <= MAT[i][j] <= 10^6
Time Limit: 1 sec
In this approach, we will check every element of the matrix, and for each negative number, we will increment our answer by 1. We will use two nested loops to traverse the given matrix and a variable ‘COUNT’ to store the count of the negative numbers. The final value of ‘COUNT’ will be our answer.
Algorithm :
In this approach, we will use the fact that each row is sorted in non-increasing order. This means all the numbers lying left to a negative number will be negative. So, we will try to find a negative number in each row using binary search. For each row, we will start with the middle number. If the middle number is negative, we will skip searching the right partition and search for more negative numbers in the left partition. If the middle number is not negative, we will skip searching the left partition and search for negative numbers in the right partition.
Algorithm :
In this approach, we will use the fact that the matrix is sorted in non-increasing order, both row-wise and column-wise. For every negative number, all the numbers lying to its left and down will also be negative. We will start traversing the row from the rightmost element for every row starting from the top row. Now two cases arise:
Algorithm :