forked from coder2hacker/Explore-open-source
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlargest_island copy.cpp
67 lines (48 loc) · 1.34 KB
/
largest_island copy.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
#include<iostream>
#include <vector>
using namespace std;
int dfs(vector<vector<int> > &matrix, vector<vector<bool> > &visited, int i,int j,int m,int n){
visited[i][j] = true;
int cs = 1;
int dx[] = {1,-1,0,0};
int dy[] = {0,0,1,-1};
for(int k=0;k<4;k++){
int nx = i + dx[k];
int ny = j + dy[k];
if(nx>=0 and nx<m and ny>=0 and ny<n and matrix[nx][ny]==1 and !visited[nx][ny]){
int subcomponent = dfs(matrix,visited,nx,ny,m,n);
cs += subcomponent;
}
}
return cs;
}
int largest_island(vector<vector<int> > matrix){
//return the size of largest island in grid
int m = matrix.size();
int n = matrix[0].size();
//visited matrix
vector<vector<bool> > visited(m, vector<bool>(n,false));
int largest = 0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(!visited[i][j] and matrix[i][j]==1){
int size = dfs(matrix,visited,i,j,m,n);
if(size>largest){
largest = size;
}
}
}
}
return largest;
}
int main(){
vector<vector<int> > grid = {
{1, 0, 0, 1, 0},
{1, 0, 1, 0, 0},
{0, 0, 1, 0, 1},
{1, 0, 1, 1, 1},
{1, 0, 1, 1, 0}
};
cout<< largest_island(grid) <<endl;
return 0;
}