Unsafe elements in a matrix

4

21 votes
Arrays, Data Structures, Multi-dimensional
Problem

You have a matrix S consisting of N rows and M columns. Let u be the maximum element of the matrix and v be the smallest element of the matrix. If any element whose value is equal to u or v are called unsafe elements and they disfigure the complete row and column of the matrix. More formally, if any element is equal to u or v and contains cell number (x, y), that is, S[x][y]=u or S[x][y]=v are unsafe so that they also disfigure all the cells that have row x or column y and also are unsafe.

Your task is to find the number of safe elements.

Input format

  • The first line contains T denoting the number of test cases.
  • The first line of each test case consists of two space-separated integers N and M.
  • Next N lines consist of M space-separated integers.

Output format

For each test case, print a single integer denoting the safe elements.

Constraints

1T100000

1NM1e5

1S(i,j)1e5   i[1,N]  j[1,M]

Sum of N×M over all test cases does not exceed 1e6

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

It is clear that max element in the matrix is 12 and minimum is 1.Since the cell number of 12 is (3,1) all the cells which have row three and column will be unsafe.

8 8 3       
6 2 4       
12 1 2

The minimum element of the matrix is 1 so cell number is (3,2) so all the cells which have column number 2 and row number 3 will also be under attack.

8 8 3
6 2 4
12 1 2

Only safe elements are 3 and 4 so answer is 2.

Editor Image

?