1. Flip Each Zero and Run Full Grid BFS
Intuition
Test every candidate zero. For each zero at (r, c), temporarily change grid[r][c] = 1. Launch a BFS flood-fill from (r, c) to calculate the connected island size, update the global maximum, and restore grid[r][c] = 0.
Algorithm
- Initialize maxIsland = initial island max.
- Loop r from 0 to n - 1 and c from 0 to n - 1:
- If grid[r][c] == 0:
- grid[r][c] = 1.
- Run BFS from (r, c) to find island size.
- maxIsland = max(maxIsland, size).
- grid[r][c] = 0 (backtrack).
- Return maxIsland.
#include <iostream>#include <vector>#include <queue>#include <algorithm> class Solution { int getIslandSize(int sr, int sc, const std::vector<std::vector<int>>& grid) { int n = grid.size(); std::vector<std::vector<bool>> visited(n, std::vector<bool>(n, false)); std::queue<std::pair<int, int>> q; q.push({sr, sc}); visited[sr][sc] = true; int size = 0; int dr[] = {-1, 1, 0, 0}; int dc[] = {0, 0, -1, 1}; while (!q.empty()) { auto [r, c] = q.front(); q.pop(); size++; for (int k = 0; k < 4; ++k) { int nr = r + dr[k], nc = c + dc[k]; if (nr >= 0 && nr < n && nc >= 0 && nc < n && !visited[nr][nc] && grid[nr][nc] == 1) { visited[nr][nc] = true; q.push({nr, nc}); } } } return size; }public: int largestIsland(std::vector<std::vector<int>>& grid) { int n = grid.size(); int maxIsland = 0; bool hasZero = false; for (int r = 0; r < n; ++r) { for (int c = 0; c < n; ++c) { if (grid[r][c] == 0) { hasZero = true; grid[r][c] = 1; maxIsland = std::max(maxIsland, getIslandSize(r, c, grid)); grid[r][c] = 0; } } } return hasZero ? maxIsland : n * n; }}; int main() { Solution sol; std::vector<std::vector<int>> grid = {{1, 0}, {0, 1}}; std::cout << "Brute force island: " << sol.largestIsland(grid) << " (Expected: 3)\n"; return 0;}Time & Space Complexity
- Time complexity:
O(n^4) - Space complexity:
O(n^2)