-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path695. [PRAC] Max Area of Island
67 lines (57 loc) · 2.08 KB
/
695. [PRAC] Max Area of Island
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
vector<int> direction{-1, 0, 1, 0, -1};
class Solution {
public:
int dfs(vector<vector<int>> & grid, int r, int c){
if(grid[r][c] == 0) return 0;
grid[r][c] = 0;
int x, y, area = 1;
for(int i=0; i<4; i++){
x = r+direction[i];
y = c+direction[i+1];
if(x>=0 && x<grid.size() && y>=0 && y<grid[0].size()){
area += dfs(grid, x, y);
}
}
return area;
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
if(grid.empty() || grid[0].empty()) return 0;
int max_area = 0;
for(int i=0; i<grid.size(); ++i){
for(int j=0; j<grid[0].size(); ++j){
if(grid[i][j] == 1){
max_area = max(max_area, dfs(grid, i, j));
}
}
}
return max_area;
// int m=grid.size();
// int n=m?grid[0].size():0;
// int local_area, area=0, x, y;
// for(int i=0; i<m; i++){
// for(int j=0; j<n; j++){
// if(grid[i][j]){
// local_area = 1;
// grid[i][j] = 0;
// stack<pair<int, int>> island;
// island.push({i,j});
// while(!island.empty()){
// auto [r,c] = island.top();
// island.pop();
// for(int k=0; k<4; ++k) {
// x = r + direction[k], y = c+direction[k+1];
// if(x >= 0 && x < m &&
// y >= 0 && y < n && grid[x][y] == 1){
// grid[x][y] = 0;
// ++local_area;
// island.push({x,y});
// }
// }
// }
// area = max(area, local_area);
// }
// }
// }
// return area;
}
};