Skip to content

Commit da577b8

Browse files
committed
🚀 13-Sep-2020
1 parent 401b153 commit da577b8

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
Given a rows x cols matrix mat, where mat[i][j] is either 0 or 1, return the number of special positions in mat.
2+
3+
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).
4+
5+
6+
7+
Example 1:
8+
9+
Input: mat = [[1,0,0],
10+
[0,0,1],
11+
[1,0,0]]
12+
Output: 1
13+
Explanation: (1,2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0.
14+
Example 2:
15+
16+
Input: mat = [[1,0,0],
17+
[0,1,0],
18+
[0,0,1]]
19+
Output: 3
20+
Explanation: (0,0), (1,1) and (2,2) are special positions.
21+
Example 3:
22+
23+
Input: mat = [[0,0,0,1],
24+
[1,0,0,0],
25+
[0,1,1,0],
26+
[0,0,0,0]]
27+
Output: 2
28+
Example 4:
29+
30+
Input: mat = [[0,0,0,0,0],
31+
[1,0,0,0,0],
32+
[0,1,0,0,0],
33+
[0,0,1,0,0],
34+
[0,0,0,1,1]]
35+
Output: 3
36+
37+
38+
Constraints:
39+
40+
rows == mat.length
41+
cols == mat[i].length
42+
1 <= rows, cols <= 100
43+
mat[i][j] is 0 or 1.
44+
45+
46+
47+
48+
49+
50+
51+
52+
class Solution {
53+
public:
54+
55+
bool isSpecial(vector<vector<int> > &mat, int i, int j){
56+
int m=mat.size();
57+
int n=mat[0].size();
58+
59+
for(int x=0;x<n;x++)
60+
if(mat[i][x]==1 && x!=j) return false;
61+
62+
for(int x=0;x<m;x++)
63+
if(mat[x][j]==1 && x!=i) return false;
64+
65+
return true;
66+
}
67+
68+
int numSpecial(vector<vector<int>>& mat) {
69+
70+
int m=mat.size();
71+
if(m==0) return 0;
72+
int n=mat[0].size();
73+
74+
int cnt=0;
75+
76+
for(int i=0;i<m;i++){
77+
for(int j=0;j<n;j++){
78+
if(mat[i][j] && isSpecial(mat, i, j))
79+
cnt++;
80+
}
81+
}
82+
return cnt;
83+
}
84+
};
85+
86+
87+
88+
89+
90+
/* Alter
91+
1. Get the sum of all the rows
92+
2. Get the sum of all the coloumns
93+
3. Traverse the matrix and whenever encounter 1 check its row and col sum, if 1 then increment count by 1.
94+
4. Return count
95+
*/

0 commit comments

Comments
 (0)