forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
64 lines (49 loc) · 1.37 KB
/
main.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
/// Source : https://leetcode.com/problems/max-area-of-island/description/
/// Author : liuyubobobo
/// Time : 2017-10-19
#include <iostream>
#include <cassert>
#include <vector>
using namespace std;
// floodfill
// Time Complexity: O(n*m)
// Space Complexity: O(n*m)
class Solution {
private:
int d[4][2] = {{0,1}, {0,-1}, {1,0}, {-1,0}};
int n, m;
bool visited[50][50];
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
n = grid.size();
assert(n > 0);
m = grid[0].size();
for(int i = 0 ; i < n ; i ++)
for(int j = 0 ; j < m ; j ++)
visited[i][j] = false;
int res = 0;
for(int i = 0 ; i < n ; i ++)
for(int j = 0 ; j < m ; j ++)
if(!visited[i][j] && grid[i][j] == 1)
res = max(res, dfs(grid, i, j));
return res;
}
private:
bool inArea(int x, int y){
return x >= 0 && x < n && y >= 0 && y < m;
}
int dfs(const vector<vector<int>>& grid, int x, int y){
visited[x][y] = true;
int res = 1;
for(int i = 0 ; i < 4 ; i ++){
int newx = x + d[i][0];
int newy = y + d[i][1];
if(inArea(newx, newy) && !visited[newx][newy] && grid[newx][newy] == 1)
res += dfs(grid, newx, newy);
}
return res;
}
};
int main() {
return 0;
}