[LeetCode] Special Positions in a Binary Matrix

1582. Special Positions in a Binary Matrix

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).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int numSpecial(vector<vector<int>>& mat) {
int n = mat.size(), m = mat[0].size();
vector<int> r(n), c(m);
for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) {
r[i] += mat[i][j];
c[j] += mat[i][j];
}
int res = 0;
for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) {
res += (r[i] == 1 and c[j] == 1 and mat[i][j] == 1);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/12/13/PS/LeetCode/special-positions-in-a-binary-matrix/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.