class Solution { private: int size[507 * 507]; int fa[507 * 507]; void _init() { for(int i=0;i<=n * m;i++) fa[i] = i, size[i] = 1; } int _find(int x) { if(fa[x] == x) return x; else return fa[x] = _find(fa[x]); } int maxSize = 1; void _union(int u,int v) { int fau = _find(u); int fav = _find(v); if(fau == fav) return ; fa[fau] = fav; size[fav] += size[fau]; maxSize = max(maxSize, size[fav]); } int n, m; int get(int x, int y) { return x * n + y; } bool edge(int x, int y) { if(x < 0 || x >= n || y < 0 || y >= m) return false; return true; } public: int largestIsland(vector<vector<int>>& grid) { n = grid.size(); m = grid[0].size(); _init(); int dx[4] = {0, 0, -1, 1}; int dy[4] = {-1, 1, 0, 0}; for(int i = 0; i < n; i ++) { for(int j = 0; j < m; j ++) { if(!grid[i][j]) continue; for(int to = 0; to < 4; to ++) { int tx = i + dx[to]; int ty = j + dy[to]; if(edge(tx, ty) && grid[tx][ty]) { _union(get(i,j), get(tx,ty)); } } } } unordered_map<int,int> mp; for(int i = 0;i < n; i ++) { for(int j = 0; j < m; j ++) { if(grid[i][j]) continue; for(int to = 0; to < 4; to ++) { int tx = i + dx[to]; int ty = j + dy[to]; if(!edge(tx, ty)) continue; if(grid[tx][ty] == 0) continue; int fa = _find(get(tx, ty)); mp[fa] = size[fa]; } int total = 1; for(unordered_map<int,int> ::iterator it = mp.begin(); it != mp.end(); it ++) { total += it->second; } //for(auto at: mp) total += at.second; maxSize = max(maxSize, total); mp.clear(); } } return maxSize; } };