Sponsored
Sponsored
This approach involves iterating through each element of the matrix and checking if it is '1'. For each such element, all other elements in its row and column are checked to ensure they are '0'. This approach is straightforward but can be optimized.
Time Complexity: O(m * n * (m + n)), where m is the number of rows and n is the number of columns.
Space Complexity: O(1), since we use a constant amount of space.
1function numSpecial(mat) {
2 const m = mat.length;
3 const n = mat[0].length;
4 let specialCount = 0;
5 for (let i = 0; i < m; i++) {
6 for (let j = 0; j < n; j++) {
7 if (mat[i][j] === 1) {
8 let isSpecial = true;
9 for (let k = 0; k < m; k++) {
10 if (k !== i && mat[k][j] === 1) {
11 isSpecial = false;
12 break;
13 }
14 }
15 for (let k = 0; k < n; k++) {
16 if (k !== j && mat[i][k] === 1) {
17 isSpecial = false;
18 break;
19 }
20 }
21 if (isSpecial) specialCount++;
22 }
23 }
24 }
25 return specialCount;
26}
This JavaScript solution iterates over the matrix with nested loops. Each '1' triggers row and column scans to confirm no other '1's are present, verifying the uniqueness and thus special status of the position.
In this approach, two auxiliary arrays are used to track the number of '1's in each row and column. The matrix is then iterated to find the positions where both the row and column contain exactly one '1'. This approach reduces the need for repeatedly checking rows and columns.
Time Complexity: O(m * n), because we only iterate through the matrix twice.
Space Complexity: O(m + n), for storing row and column counts.
using namespace std;
class Solution {
public:
int numSpecial(vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
vector<int> rowOnes(m, 0), colOnes(n, 0);
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (mat[i][j] == 1) {
rowOnes[i]++;
colOnes[j]++;
}
}
}
int specialCount = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (mat[i][j] == 1 && rowOnes[i] == 1 && colOnes[j] == 1) {
specialCount++;
}
}
}
return specialCount;
}
};
The C++ version uses vectors to store the number of '1's in each row and column. Positions are then checked for the special condition where only one '1' exists in the respective row and column.