LeetCode——1582. Special position in binary matrix

Title description:

Give you a matrix mat of size rows x cols, where mat[i][j] is 0 or 1, please return the number of special positions in the matrix mat.
Special position definition: If mat[i][j] == 1 and all other elements in the i-th row and j-th column are 0 (the subscripts of the rows and columns start from 0), then the position (i, j ) Is called a special location.

Tip:
rows == mat.length
cols == mat[i].length
1 <= rows, cols <= 100
mat[i][j] is 0 or 1

Example 1:
Input: mat = [[1,0,0],
[0,0,1],
[1,0,0]]
Output: 1
Explanation: (1,2) is a special position because mat[ 1][2] == 1 and all other elements in the row and column are 0

Example 2:
Input: mat = [[1,0,0],
[0,1,0],
[0,0,1]]
Output: 3
Explanation: (0,0), (1,1) and ( 2, 2) are all special locations

Example 3:
Input: MAT = [[0,0,0,1],
[1,0,0,0],
[0,1,1,0],
[0,0,0,0]]
Output: 2

Example 4:
Input: mat = [[0,0,0,0,0],
[1,0,0,0,0],
[ 0,1,0,0,0 ],
[0,0,1 ,0,0],
[0,0,0,1,1]]
output: 3

code show as below:

class Solution {
    
    
    public int numSpecial(int[][] mat) {
    
    
        int m = mat.length;
        int n = mat[0].length;
        int ans = 0, sum1, sum2;
        for (int i = 0; i < m; i++) {
    
    
            for (int j = 0; j < n; j++) {
    
    
                sum1 = 0;
                sum2 = 0;
                if (mat[i][j] == 1) {
    
    
                    for (int k = 0; k < n; k++) {
    
    
                        sum1 += mat[i][k];
                    }
                    for (int l = 0; l < m; l++) {
    
    
                        sum2 += mat[l][j];
                    }
                }
                if (sum1 == 1 && sum2 == 1) {
    
    
                    ans++;
                }
            }
        }
        return ans;
    }
}

Results of the:
Insert picture description here

Guess you like

Origin blog.csdn.net/FYPPPP/article/details/114225945