classSolution{public:intlargestIsland(vector<vector<int>>&grid){constintm=grid.size();constintn=grid[0].size();intmaxSize=0;// sizes[i] := size of i-th connected component (start from 2)vector<int>sizes{0,0};// For each 1 in the grid, paint all connected 1 with the next available// Color (2, 3, and so on). Also, remember the size of the island we just// Painted with that color.for(inti=0;i<m;++i)for(intj=0;j<n;++j)if(grid[i][j]==1)sizes.push_back(paint(grid,i,j,sizes.size()));// Paint 2, 3, ...for(inti=0;i<m;++i)for(intj=0;j<n;++j)if(grid[i][j]==0){constunordered_set<int>neighborIds{getId(grid,i+1,j),getId(grid,i-1,j),getId(grid,i,j+1),getId(grid,i,j-1)};maxSize=max(maxSize,1+getSize(neighborIds,sizes));}returnmaxSize==0?m*n:maxSize;}private:intpaint(vector<vector<int>>&grid,inti,intj,intid){if(i<0||i==grid.size()||j<0||j==grid[0].size())return0;if(grid[i][j]!=1)return0;grid[i][j]=id;// grid[i][j] is part of id-th connected componentreturn1+paint(grid,i+1,j,id)+paint(grid,i-1,j,id)+paint(grid,i,j+1,id)+paint(grid,i,j-1,id);}// Get the id of grid[i][j], return 0 if out of boundintgetId(constvector<vector<int>>&grid,inti,intj){if(i<0||i==grid.size()||j<0||j==grid[0].size())return0;// Invalidreturngrid[i][j];}intgetSize(constunordered_set<int>&neighborIds,constvector<int>&sizes){intsize=0;for(constintneighborId:neighborIds)size+=sizes[neighborId];returnsize;}};
classSolution{publicintlargestIsland(int[][]grid){finalintm=grid.length;finalintn=grid[0].length;intmaxSize=0;// sizes[i] := size of i-th connected component (start from 2)List<Integer>sizes=newArrayList<>(Arrays.asList(0,0));// For each 1 in the grid, paint all connected 1 with the next available// Color (2, 3, and so on). Also, remember the size of the island we just// Painted with that color.for(inti=0;i<m;++i)for(intj=0;j<n;++j)if(grid[i][j]==1){sizes.add(paint(grid,i,j,sizes.size()));// Paint 2, 3, ...}for(inti=0;i<m;++i)for(intj=0;j<n;++j)if(grid[i][j]==0){Set<Integer>neighborIds=newHashSet<>(Arrays.asList(getId(grid,i-1,j),getId(grid,i+1,j),getId(grid,i,j+1),getId(grid,i,j-1)));maxSize=Math.max(maxSize,1+getSize(grid,neighborIds,sizes));}returnmaxSize==0?m*n:maxSize;}privateintpaint(int[][]grid,inti,intj,intid){if(i<0||i==grid.length||j<0||j==grid[0].length)return0;if(grid[i][j]!=1)return0;grid[i][j]=id;// grid[i][j] is part of id-th connected componentreturn1+paint(grid,i+1,j,id)+paint(grid,i-1,j,id)+paint(grid,i,j+1,id)+paint(grid,i,j-1,id);}// Get the id of grid[i][j], return 0 if out of boundprivateintgetId(int[][]grid,inti,intj){if(i<0||i==grid.length||j<0||j==grid[0].length)return0;// Invalidreturngrid[i][j];}privateintgetSize(int[][]grid,Set<Integer>neighborIds,List<Integer>sizes){intsize=0;for(finalintneighborId:neighborIds)size+=sizes.get(neighborId);returnsize;}}