-
Notifications
You must be signed in to change notification settings - Fork 0
/
2disland.cpp
71 lines (58 loc) · 1.57 KB
/
2disland.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
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
/* Find the size of the biggest island in a boolean grid */
bool isSafe(int r, int c, vector<vector<bool>>& grid, vector<vector<bool>>& vvisited) {
return (r>=0 && r<grid.size() &&
c>=0 && c<grid.at(r).size() &&
grid.at(r).at(c) && !vvisited.at(r).at(c));
}
int DFS(int r, int c, vector<vector<bool>>& grid, vector<vector<bool>>&
vvisited, int count) {
static int rowNbr[] = {-1, 1, 0, 0, -1, -1, 1, 1};
static int colNbr[] = {0, 0, -1, 1, -1, 1, -1, 1};
vvisited.at(r).at(c) = true;
if(grid.at(r).at(c) == false)
return 0;
for(int k=0; k<8; k++) {
if(isSafe(r+rowNbr[k], c+colNbr[k], grid, vvisited)) {
count = DFS(r+rowNbr[k], c+colNbr[k], grid, vvisited, count);
}
}
return ++count;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int rows, cols;
int maxnodes = 0;
cin >> rows;
cin >> cols;
vector<vector<bool>> grid;
vector<vector<bool>> vvisited;
//construct the input grid
for(int i=0; i<rows; i++) {
grid.push_back(vector<bool>());
vvisited.push_back(vector<bool>());
for(int j=0; j<cols; j++) {
bool input;
cin >> input;
grid.at(i).push_back(input);
vvisited.at(i).push_back(false);
}
}
//now begin finding size of the biggest island
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
if(!vvisited.at(i).at(j)) {
int count = DFS(i, j, grid, vvisited, 0);
if(count > maxnodes)
maxnodes = count;
}
}
}
cout << maxnodes;
return 0;
}