-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Making A Large Island.cpp
75 lines (64 loc) · 2.17 KB
/
Making A Large Island.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
70
71
72
73
74
75
/*
Company Tags : Google, Uber
Leetcode Link : https://leetcode.com/problems/making-a-large-island/
Reference : https://www.youtube.com/watch?v=_426VVOB8Vo
*/
class Solution {
public:
int m, n;
vector<vector<int>> directions{{1, 0}, {-1, 0},{0, 1},{0, -1}};
int DFS(vector<vector<int>>& grid, int i, int j, int& id) {
if(i < 0 || i >= m || j < 0 || j >= n || grid[i][j] != 1)
return 0;
grid[i][j] = id;
int count = 1;
for(vector<int>& dir : directions) {
int x = i + dir[0];
int y = j + dir[1];
count += DFS(grid, x, y, id);
}
return count;
}
int largestIsland(vector<vector<int>>& grid) {
m = grid.size();
n = grid[0].size();
int maxArea = 0;
unordered_map<int, int> mp;
int island_id = 2;
for(int i = 0; i<m; i++) {
for(int j = 0; j<n; j++) {
if(grid[i][j] == 1) {
int size = DFS(grid, i, j, island_id);
maxArea = max(maxArea, size);
mp[island_id] = size;
island_id++;
}
}
}
for(int i = 0; i<m; i++) {
for(int j = 0; j<n; j++) {
cout << grid[i][j] << " ";
}
cout << endl;
}
for(int i = 0; i<m; i++) {
for(int j = 0; j<n; j++) {
if(grid[i][j] == 0) {
unordered_set<int> st;
for(vector<int>& dir : directions) {
int x = i + dir[0];
int y = j + dir[1];
if(x >= 0 && x < m && y >= 0 && y < n && grid[x][y] != 0)
st.insert(grid[x][y]);
}
int sum = 1; //converting current 0 to 1
for(const int &s : st) {
sum += mp[s];
}
maxArea = max(maxArea, sum);
}
}
}
return maxArea;
}
};