mirror of
https://github.com/Manoj-HV30/dsa-competitive-programming.git
synced 2026-05-16 19:35:22 +00:00
49 lines
1.6 KiB
C++
49 lines
1.6 KiB
C++
class Solution{
|
|
public:
|
|
int numSpecial(vector<vector<int>> &mat){
|
|
int ans = 0;
|
|
int m = mat.size();
|
|
int n = mat[0].size();
|
|
for(int row = 0;row<m;row++){
|
|
int colIndex = -1;
|
|
int count = 0;
|
|
for(int col = 0;col<n;col++){
|
|
if(mat[row][col]==1){
|
|
count++;
|
|
colIndex = col;
|
|
}
|
|
}
|
|
if(count==1){
|
|
bool good = true;
|
|
for(int r=0;r<m;r++){
|
|
|
|
if(r!=row && mat[r][colIndex]==1) {
|
|
good = false;
|
|
break;
|
|
}
|
|
}
|
|
if(good) ans++;
|
|
}
|
|
}
|
|
return ans;
|
|
}
|
|
};
|
|
|
|
/*
|
|
Approach:
|
|
|
|
We iterate through each row of the matrix and count how many 1s appear in that row.
|
|
While scanning the row, we also record the column index where the 1 occurs. If a row
|
|
contains exactly one 1, it becomes a candidate for a special position. For that candidate,
|
|
we then check the entire column corresponding to that 1 to ensure no other row contains a 1
|
|
in the same column. If the column also has exactly one 1 (the current position), then that
|
|
position satisfies both conditions and we increment the answer. After checking all rows,
|
|
the total number of such positions is returned.
|
|
|
|
Time Complexity: O(mn + m²) in the worst case. We scan each row once (mn work), and for
|
|
rows that contain exactly one 1 we scan the column (up to m operations). In practice this
|
|
is usually closer to O(mn).
|
|
|
|
Space Complexity: O(1)
|
|
*/
|