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.
1#include <stdio.h>
2
3int numSpecial(int** mat, int matSize, int* matColSize){
4 int specialCount = 0;
5 for (int i = 0; i < matSize; ++i) {
6 for (int j = 0; j < matColSize[i]; ++j) {
7 if (mat[i][j] == 1) {
8 int isSpecial = 1;
9 for (int k = 0; k < matSize; ++k) {
10 if (k != i && mat[k][j] == 1) {
11 isSpecial = 0;
12 break;
13 }
14 }
15 for (int k = 0; k < matColSize[i]; ++k) {
16 if (k != j && mat[i][k] == 1) {
17 isSpecial = 0;
18 break;
19 }
20 }
21 if (isSpecial) specialCount++;
22 }
23 }
24 }
25 return specialCount;
26}
The function numSpecial iterates over each element in the matrix. For each '1' found, it checks the entire row and column to identify if it's a special position by ensuring all other elements in the row and column are '0'.
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.
1
This function first calculates the number of '1's in each row and column using two arrays. A second iteration through the matrix identifies special positions by checking if the respective row and column have exactly one '1'.