Count the cells in a binary matrix that are the only 1 in both their row and their column.
Given an binary matrix, count how many cells contain a 1 such that every other cell in the same row and every other cell in the same column is 0.
A cell is considered special if it is the only 1 in its row and also the only 1 in its column.
Input Format
- A binary matrix
matwithmrows andncolumns. - Each entry is either
0or1.
You may assume the matrix is non-empty.
Output Format
- Return the number of special positions in the matrix.
Constraints
mat[i][j]is either0or1- The matrix size is small enough for an solution
Example 1
Input
mat = [[1,0,0],[0,0,1],[1,0,0]]
Output
1
Explanation
The only special position is at row 2, column 3 (0-indexed: [1][2]). It is the only 1 in its row and its column.
Example 2
Input
mat = [[1,0,0],[0,1,0],[0,0,1]]
Output
3
Explanation
Each diagonal 1 is the only 1 in both its row and its column.
Show 1 more example
Example 3
Input
mat = [[0,0],[0,0]]
Output
0
Explanation
There are no 1s, so there are no special positions.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.