-
Notifications
You must be signed in to change notification settings - Fork 8
/
count-largest-connected-component.cpp
96 lines (95 loc) · 3.02 KB
/
count-largest-connected-component.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
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
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define mkp make_pair
int main() {
ll t;
cin>>t;
while(t--)
{
ll n,m;
cin>>n>>m;
ll a[n][m];
ll v[n*m];
for(ll i=0;i<(n*m);i++)
{
cin>>v[i];
}
ll k=0;
for(ll i=0;i<n;i++)
{
for(ll j=0;j<m;j++)
{
a[i][j]=v[k];
k++;
}
}
ll c=0,count=INT_MIN;
bool visited[n][m];
memset(visited,false,sizeof(visited));
for(ll i=0;i<n;i++)
{
for(ll j=0;j<m;j++)
{
if(a[i][j]==1 && !visited[i][j])
{
c=0;
//cout<<c<<endl;
stack<pair<ll,ll> > s;
s.push(mkp(i,j));
visited[i][j]=true;
while(!s.empty())
{
ll u=s.top().first;
ll v=s.top().second;
//cout<<u<<" "<<v<<endl;
c++;
//cout<<c<<endl;
s.pop();
if(u+1<n && v+1<m && a[u+1][v+1]==1 && !visited[u+1][v+1])
{
s.push(mkp(u+1,v+1));
visited[u+1][v+1]=true;
}
if(u-1>=0 && v-1>=0 &&a[u-1][v-1]==1 && !visited[u-1][v-1])
{
s.push(mkp(u-1,v-1));
visited[u-1][v-1]=true;
}
if(u-1>=0 && v+1<m && a[u-1][v+1]==1 && !visited[u-1][v+1])
{
s.push(mkp(u-1,v+1));
visited[u-1][v+1]=true;
}
if(u+1<n && v-1>=0 && a[u+1][v-1]==1 && !visited[u+1][v-1])
{
s.push(mkp(u+1,v-1));
visited[u+1][v-1]=true;
}
if(u-1>=0 && a[u-1][v]==1 && !visited[u-1][v])
{
s.push(mkp(u-1,v));
visited[u-1][v]=true;
}
if(u+1<n && a[u+1][v]==1 && !visited[u+1][v])
{
s.push(mkp(u+1,v));
visited[u+1][v]=true;
}
if(v+1<m && a[u][v+1]==1 && !visited[u][v+1]){
s.push(mkp(u,v+1));
visited[u][v+1]=true;
}
if(v-1>=0 && a[u][v-1]==1 && !visited[u][v-1]){
s.push(mkp(u,v-1));
visited[u][v-1]=true;
}
}
count=max(count,c);
}
}
}
cout<<count<<endl;
}
return 0;
}