-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNo.OfIsland.cpp
68 lines (62 loc) · 1.63 KB
/
No.OfIsland.cpp
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
60
61
62
63
64
65
66
67
68
//author @Nishant
#include<bits/stdc++.h>
using namespace std;
int totalBridges(int **mat, int n, int m);
void removeIsland(int **mat, int n, int m, int i, int j);
bool isSafe(int n, int m, int i, int j);
int main(){
int m, n;
cin >> n >> m;
int **mat = (int **)malloc(n * sizeof(int *));
for(int i=0; i<n; i++){
mat[i] = (int *)malloc(m * sizeof(int));
}
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
cin >> mat[i][j];
}
}
// for(int i=0; i<m; i++){
// cout << endl;
// for(int j=0; j<n; j++){
// cout << mat[i][j] << "\t";
// }
// }
cout << totalBridges(mat, n, m);
return 0;
}
int totalBridges(int **mat, int n, int m){
int count = 0;
//cout << mat[0][0] << endl;
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
if(mat[i][j] == 1){
count++;
removeIsland(mat, n, m, i, j);
}
}
}
return count - 1;
}
void removeIsland(int **mat, int n, int m, int i, int j){
if(isSafe(n, m, i, j) && mat[i][j]==1){
mat[i][j] = 0;
removeIsland(mat, n, m, i - 1, j - 1);
removeIsland(mat, n, m, i - 1, j);
removeIsland(mat, n, m, i - 1, j + 1);
removeIsland(mat, n, m, i, j - 1);
removeIsland(mat, n, m, i, j + 1);
removeIsland(mat, n, m, i + 1, j - 1);
removeIsland(mat, n, m, i + 1, j);
removeIsland(mat, n, m, i + 1, j + 1);
}
}
bool isSafe(int n, int m, int i, int j){
if(i<0 || i>=n){
return false;
}
if(j<0 || j>=m){
return false;
}
return true;
}