-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathnumberofIslands.cpp
More file actions
120 lines (74 loc) · 2.57 KB
/
numberofIslands.cpp
File metadata and controls
120 lines (74 loc) · 2.57 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include<bits/stdc++.h>
#define pushb push_back
#define popf pop_front
#define MAX 200
using namespace std;
int matrix[MAX][MAX]={0};
int visited[MAX][MAX]={0};
void printTable(int r,int c){
for(int i=0;i<=r;i++){
for(int j=0;j<=r;j++){
cout<<matrix[i][j]<<" ";
}
cout<<endl;
}
}
void input(int r,int c){
for(int i=1;i<=r;i++){
for(int j=1;j<=c;j++){
int ele;cin>>ele;
matrix[i][j]=ele;
}
}
// printTable(r,c);
}
void printDeque(deque<pair<int,int> >arr){
for(deque<pair<int,int> >::iterator i=arr.begin();i!=arr.end();i++){
cout<<"("<<(*i).first<<","<<(*i).second<<")"<<",\t";
}
cout<<endl;
}
void getMaxConnection(int r,int c){
int count=0;
for(int i=0;i<=r;i++){
for(int j=0;j<=c;j++){
if(matrix[i][j]==1 && visited[i][j]==0){
deque<pair<int,int> >pairs;
if(pairs.size()==0)
count++;
pairs.pushb({i,j});
visited[i][j]=1;
while(!pairs.empty()){
int x=pairs.front().first;
int y=pairs.front().second;
//cout<<"\nDEQUEUE OBTAINED :"<<endl;
//printDeque(pairs);
pairs.popf();
if(matrix[x][y+1]==1 && visited[x][y+1]==0){
pairs.pushb({x,y+1});
visited[x][y+1]=1;
}
if(matrix[x+1][y]==1 && visited[x+1][y]==0){
pairs.pushb({x+1,y});
visited[x+1][y]=1;
}
if(matrix[x][y-1]==1 && visited[x][y-1]==0){
visited[x][y-1]=1;
pairs.pushb({x,y-1});
}
if(matrix[x-1][y]==1 && visited[x-1][y]==0){
visited[x-1][y]=1;
pairs.pushb({x-1,y});
}
}
}
}
}
cout<<count<<endl;
}
int main(){
int r,c;cin>>r>>c;
input(r,c);
getMaxConnection(r,c);
return 0;
}