-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode-MaxAreaOfIsland.cpp
More file actions
72 lines (54 loc) · 1.89 KB
/
Copy pathLeetCode-MaxAreaOfIsland.cpp
File metadata and controls
72 lines (54 loc) · 1.89 KB
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
struct graph {
map<pair<int, int>, set<pair<int, int>>> list;
void add_edge(pair<int, int> u, pair<int, int> v) {
list[u].insert(v);
list[v].insert(u);
}
};
int dfs(graph& g, vector<vector<int>>& grid) {
int n = grid.size();
int m = grid[0].size();
set<pair<int, int>> visited;
int area = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (grid[i][j] == 0) continue;
if (visited.count({i, j}) > 0) continue;
stack<pair<int, int>> s;
int count = 0;
s.push({i, j});
while (!s.empty()) {
pair<int, int> u = s.top();
s.pop();
if (visited.count(u) <= 0) {
visited.insert(u);
++count;
for (pair<int, int> v: g.list[u]) {
s.push(v);
}
}
}
area = max(area, count);
}
}
return area;
}
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int n = grid.size();
int m = grid[0].size();
graph g;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (grid[i][j] == 0) continue;
if (j > 0 && grid[i][j-1] == 1) g.add_edge({i, j - 1}, {i, j}); //left
if (i > 0 && grid[i-1][j] == 1) g.add_edge({i-1, j}, {i, j}); //up
if (j + 1 < m && grid[i][j+1] == 1) g.add_edge({i, j + 1}, {i, j});//right
if (i + 1 < n && grid[i+1][j] == 1) g.add_edge({i+1, j}, {i, j});//down
}
}
int area = dfs(g, grid);
return area;
}
};