-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum connected group.cpp
73 lines (68 loc) · 1.82 KB
/
maximum connected group.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
class Solution {
public:
int n;
int arr[4]={-1,1,0,0};
int brr[4]={0,0,-1,1};
int solve(int i,int j,vector<vector<int>>&grid,int k)
{
grid[i][j]=k;
int count=0;
for(int l=0;l<4;l++)
{
int x=i+arr[l];
int y=j+brr[l];
if(x>=0 && x<n && y>=0 && y<n && grid[x][y]==1)
{
count+=solve(x,y,grid,k);
}
}
return count+1;
}
int MaxConnection(vector<vector<int>>& grid) {
// code here
n=grid.size();
int k=2;
unordered_map<int,int>mp;
mp[0]=0;
int ans=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(grid[i][j]==1)
{
int x=solve(i,j,grid,k);
ans=max(ans,x);
mp[k]=x;
++k;
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(grid[i][j]==0)
{
set<int>st;
int count=1;
for(int l=0;l<4;l++)
{
int x=arr[l]+i;
int y=brr[l]+j;
if(x>=0 && y>=0 && x<n && y<n)
{
if(st.find(grid[x][y])==st.end())
{
count+=mp[grid[x][y]];
st.insert(grid[x][y]);
}
}
}
ans=max(ans,count);
}
}
}
return ans;
}
};