LeetCode 1582. Special Positions in a Binary Matrix
考点 | 难度 |
---|---|
Matrix | Easy |
题目
Given an m x n binary matrix mat, return the number of special positions in mat.
A position (i, j)
is called special if mat[i][j] == 1
and all other elements in row i and column j are 0 (rows and columns are 0-indexed).
思路
用row[]
和col[]
记录每一行和每一列里1的个数,之后再遍历所有行和列,如果有符合条件的就给ans
加一。
答案
public int numSpecial(int[][] mat) {
int m = mat.length, n = mat[0].length, res = 0, col[] = new int[n], row[] = new int[m];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (mat[i][j] == 1){
col[j]++;
row[i]++;
}
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (mat[i][j] == 1 && row[i] == 1 && col[j] == 1) res++;
return res;
}