// Code language: C++ typedef vector<int> VI; typedef vector<VI> VII; int dir[4][2]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; classSolution { public: intlargestIsland(vector<vector<int>>& grid){ int n = grid.size(), m = grid[0].size(); VII mat(n, VI(m, 0)); // 岛屿编号 VI cnt(n * m + 7); // 记录岛屿面积 int p = 1; // 岛屿编号从 1 开始
for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (grid[i][j] == 0) continue; int sq = dfs(grid, mat, i, j, p); if (sq != 0) cnt[p++] = sq; } } int vis[4]; int ans = cnt[1]; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (grid[i][j] == 1) continue; int sq = 1; memset(vis, 0, sizeof(vis)); for (int k = 0, q = 0; k < 4; ++k) { int x = i + dir[k][0], y = j + dir[k][1]; if (x < 0 || x == n || y < 0 || y == m) continue; bool is_new = true; for (int t = 0; t < q && is_new; ++t) if (mat[x][y] == vis[t]) is_new = false; if (!is_new) continue; sq += cnt[mat[x][y]]; vis[q++] = mat[x][y]; } ans = max(ans, sq); } } return ans; }
intdfs(VII& grid, VII& mat, int i, int j, int p){ if (grid[i][j] == 0 || mat[i][j] != 0) return0; int cnt = 1; mat[i][j] = p; for (int k = 0; k < 4; ++k) { int x = i + dir[k][0], y = j + dir[k][1]; if (x < 0 || x == grid.size() || y < 0 || y == grid[0].size()) continue; cnt += dfs(grid, mat, x, y, p); } return cnt; } };