-
Notifications
You must be signed in to change notification settings - Fork 1
/
25 December Missing number in matrix
59 lines (58 loc) · 1.49 KB
/
25 December Missing number in matrix
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution {
public:
long long int MissingNo(vector<vector<int> >& matrix) {
set<long long int>nonzero, zero;
// Interating through rows
for(int i = 0; i < matrix.size(); i++){
bool f = true;
long long int sum = 0;
for(int j = 0; j < matrix[0].size(); j++){
sum += matrix[i][j];
if(!matrix[i][j])
f = false;
}
if(f)nonzero.insert(sum);
if(!f)zero.insert(sum);
}
// Interating through coloumns
for(int j = 0; j < matrix[0].size(); j++){
bool f = true;
long long int sum = 0;
for(int i = 0; i < matrix.size(); i++){
sum += matrix[i][j];
if(!matrix[i][j])
f = false;
}
if(f)nonzero.insert(sum);
if(!f)zero.insert(sum);
}
// Interating through diagonals
bool f = true;
long long int sum = 0;
for(int i = 0; i < matrix.size(); i++){
sum += matrix[i][i];
if(!matrix[i][i])
f = false;
}
if(f)nonzero.insert(sum);
if(!f)zero.insert(sum);
// Interating through diagonals
f = true;
sum = 0;
for(int i = 0, j = matrix.size() - 1; j >= 0; i++,j--){
sum += matrix[i][j];
if(!matrix[i][j])
f = false;
}
if(f)nonzero.insert(sum);
if(!f)zero.insert(sum);
if(nonzero.size() == 1 and zero.size() == 1){
long long int x = *nonzero.begin();
long long int y = *zero.begin();
if(x <= y)
return -1;
return x - y;
}
return -1;
}
};