<p>You are given an <code>n x n</code> binary matrix <code>grid</code>. You are allowed to change <strong>at most one</strong> <code>0</code> to be <code>1</code>.</p>

<p>Return <em>the size of the largest <strong>island</strong> in</em> <code>grid</code> <em>after applying this operation</em>.</p>

<p>An <strong>island</strong> is a 4-directionally connected group of <code>1</code>s.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> grid = [[1,0],[0,1]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> grid = [[1,1],[1,0]]
<strong>Output:</strong> 4
<strong>Explanation: </strong>Change the 0 to 1 and make the island bigger, only one island with area = 4.</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> grid = [[1,1],[1,1]]
<strong>Output:</strong> 4
<strong>Explanation:</strong> Can&#39;t change any 0 to 1, only one island with area = 4.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>n == grid.length</code></li>
	<li><code>n == grid[i].length</code></li>
	<li><code>1 &lt;= n &lt;= 500</code></li>
	<li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>

// Naive Depth First Search
// For each 0 in the grid, let's temporarily change it to a 1, then count the size of the group from that square.
// 0 1 0 0
// 1 0 1 1
// 0 1 0 0
// 0 1 0 0

// ON^2 ON^2
class Solution {
public:
  int largestIsland(vector<vector<int>>& grid) {
      int m = grid.size();
      int n = grid[0].size();
      map<int, int> colorArea; // color -> area size
      int color = 1; // unique value for each component
      int mxArea = 0;
      for(int i = 0; i < m; i++){
          for(int j = 0; j < n; j++){
              if(grid[i][j] == 1){ // find island
                  color++;
                  int area = getArea(grid, i, j, color); // also change the value to color
                  colorArea[color] = area;
                  mxArea = max(mxArea, area);
                  
              }
          }
      }
      
     if (mxArea == m * n) return mxArea; 
     int res = 0;
      for(int i = 0; i < m; i++){
          for(int j = 0; j < n; j++){
              res = 1;
              if (grid[i][j] == 0){ // find empty
                  set<int> colors = getColors(i, j, grid); // the closest 4 neighbors 
                  for(auto it : colors){
                      res += colorArea[it];
                  }
                  mxArea = max(mxArea, res);
              }
          }
      }
      return mxArea;
  }
    
    set<int> getColors(int i, int j, vector<vector<int>>& grid){
        set<int> colors;
        vector<pair<int, int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        int m = grid.size();
        int n = grid[0].size();
        
        for(auto dir : dirs){
            int ii = i + dir.first;
            int jj = j + dir.second;
            if(ii < 0 || ii >= m || jj < 0|| jj >= n) continue;
            colors.insert(grid[ii][jj]);
        }
        return colors;
    }
    
    int getArea(vector<vector<int>>& grid, int i, int j, int color){
        int m = grid.size();
        int n = grid[0].size();
        if(i < 0 || i >= m || j < 0 || j >= n || grid[i][j] != 1) return 0;

        grid[i][j] = color;
        
        return 1 + getArea(grid, i + 1, j, color) + getArea(grid, i - 1, j, color) + getArea(grid, i, j+1, color) + getArea(grid, i, j-1, color);
        }
};

// 这道题在只有0和1的矩阵中用相连的1来表示小岛，现在说是有一个把0变为1的机会，这样原本不相邻的岛就有可能变的相邻了，从而组成一个更大的岛，让求出可能组成的最大的岛屿的面积，也就是相连的1的个数。其实大多题目的本质都是用 DFS 或者 BFS 去遍历所有相连的1，当然这道题也不例外。下面的这两种方法其实都是从每个0开始处理，先把0替换成1，然后再用 DFS 来找所有相连的1的个数，具体如何找就跟之前的岛屿的题目没啥区别了，这里就不细讲了，参见代码如下：
// 解法一：
// class Solution {
// public:
//     int largestIsland(vector<vector<int>>& grid) {
//         int m = grid.size(), n = grid[0].size(), res = 0;
//         bool hasZero = false;
//         for (int i = 0; i < m; ++i) {
//             for (int j = 0; j < n; ++j) {
//                 if (grid[i][j] == 1) continue;
//                 grid[i][j] = 1;
//                 vector<vector<bool>> visited(m, vector<bool>(n));
//                 res = max(res, helper(grid, i, j, visited));
//                 if (res == m * n) return res;
//                 grid[i][j] = 0;
//                 hasZero = true;
//             }
//         }
//         return hasZero ? res : m * n;
//     }
//     int helper(vector<vector<int>>& grid, int i, int j, vector<vector<bool>>& visited) {
//         int m = grid.size(), n = grid[0].size();
//         if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0 || visited[i][j]) return 0;
//         visited[i][j] = true;
//         return 1 + helper(grid, i - 1, j , visited) + helper(grid, i + 1, j , visited) + helper(grid, i, j - 1, visited) + helper(grid, i, j + 1, visited);
//     }
// };

// Time Complexity: O(N^4)O(N 
// 4
//  ), where NN is the length and width of the grid.

// Space Complexity: O(N^2)O(N 
// 2
//  ), the additional space used in the depth first search by stack and seen.

// 当然我们也可以用 BFS 来找所有相连的1的个数，整个的解题思路和上面的解法并没有什么不同，并不难理解，这可能就是论坛上会有人质疑这道题不应该标为 Hard 的原因，参见代码如下：
// 解法二：
// class Solution {
// public:
//     int largestIsland(vector<vector<int>>& grid) {
//         int m = grid.size(), n = grid[0].size(), res = 0;
//         bool hasZero = false;
//         vector<int> dirX{0, -1, 0, 1}, dirY{-1, 0, 1, 0};
//         for (int i = 0; i < m; ++i) {
//             for (int j = 0; j < n; ++j) {
//                 if (grid[i][j] == 1) continue;
//                 vector<vector<bool>> visited(m, vector<bool>(n));
//                 queue<int> q{{i * n + j}};
//                 int sum = 0;
//                 while (!q.empty()) {
//                     int t = q.front(); q.pop();
//                     ++sum;
//                     for (int k = 0; k < 4; ++k) {
//                         int x = t / n + dirX[k], y = t % n + dirY[k];
//                         if (x < 0 || x >= m || y < 0 || y >= n || grid[x][y] == 0 || visited[x][y]) continue;
//                         visited[x][y] = true;
//                         q.push(x * n + y);
//                     }
//                 }
//                 res = max(res, sum);
//                 if (res == m * n) return res;
//                 hasZero = true;
//             }
//         }
//         return hasZero ? res : m * n;
//     }
// };
234759