Input: mat =[[1,0,0],[0,0,1],[1,0,0]]Output: 1Explanation: (1,2)is a special position because mat[1][2]==1 and all other elements in row 1 and column 2 are 0.
A position is special if it is the only 1 in its row and column. By counting the number of 1s in each row and column, we can quickly check for each cell if it is a special position.
#include<vector>usingnamespace std;
classSolution {
public:int numSpecial(vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
vector<int> row(m), col(n);
for (int i =0; i < m; ++i)
for (int j =0; j < n; ++j)
if (mat[i][j]) { row[i]++; col[j]++; }
int ans =0;
for (int i =0; i < m; ++i)
for (int j =0; j < n; ++j)
if (mat[i][j] && row[i] ==1&& col[j] ==1) ans++;
return ans;
}
};
funcnumSpecial(mat [][]int) int {
m, n:= len(mat), len(mat[0])
row:= make([]int, m)
col:= make([]int, n)
fori:=0; i < m; i++ {
forj:=0; j < n; j++ {
ifmat[i][j] ==1 {
row[i]++col[j]++ }
}
}
ans:=0fori:=0; i < m; i++ {
forj:=0; j < n; j++ {
ifmat[i][j] ==1&&row[i] ==1&&col[j] ==1 {
ans++ }
}
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
publicintnumSpecial(int[][] mat) {
int m = mat.length, n = mat[0].length;
int[] row =newint[m], col =newint[n];
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (mat[i][j]== 1) { row[i]++; col[j]++; }
int ans = 0;
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) ans++;
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
funnumSpecial(mat: Array<IntArray>): Int {
val m = mat.size
val n = mat[0].size
val row = IntArray(m)
val col = IntArray(n)
for (i in0 until m)
for (j in0 until n)
if (mat[i][j] ==1) {
row[i]++ col[j]++ }
var ans = 0for (i in0 until m)
for (j in0 until n)
if (mat[i][j] ==1&& row[i] ==1&& col[j] ==1) ans++return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defnumSpecial(self, mat: list[list[int]]) -> int:
m, n = len(mat), len(mat[0])
row = [0]*m
col = [0]*n
for i in range(m):
for j in range(n):
if mat[i][j] ==1:
row[i] +=1 col[j] +=1 ans =0for i in range(m):
for j in range(n):
if mat[i][j] ==1and row[i] ==1and col[j] ==1:
ans +=1return ans
impl Solution {
pubfnnum_special(mat: Vec<Vec<i32>>) -> i32 {
let m = mat.len();
let n = mat[0].len();
letmut row =vec![0; m];
letmut col =vec![0; n];
for i in0..m {
for j in0..n {
if mat[i][j] ==1 {
row[i] +=1;
col[j] +=1;
}
}
}
letmut ans =0;
for i in0..m {
for j in0..n {
if mat[i][j] ==1&& row[i] ==1&& col[j] ==1 {
ans +=1;
}
}
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
numSpecial(mat: number[][]):number {
constm=mat.length, n=mat[0].length;
constrow= Array(m).fill(0), col= Array(n).fill(0);
for (leti=0; i<m; ++i)
for (letj=0; j<n; ++j)
if (mat[i][j] ===1) {
row[i]++;
col[j]++;
}
letans=0;
for (leti=0; i<m; ++i)
for (letj=0; j<n; ++j)
if (mat[i][j] ===1&&row[i] ===1&&col[j] ===1) ans++;
returnans;
}
}