827. Making A Large Island

Question:

In a 2D grid of 0s and 1s, we change at most one 0 to a 1.

After, what is the size of the largest island? (An island is a 4-directionally connected group of 1s).

Example 1:

Input: [[1, 0], [0, 1]]
Output: 3
Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
Example 2:

Input: [[1, 1], [1, 0]]
Output: 4
Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.
Example 3:

Input: [[1, 1], [1, 1]]
Output: 4
Explanation: Can't change any 0 to 1, only one island with area = 4.

Notes:

  • 1 <= grid.length = grid[0].length <= 50.
  • 0 <= grid[i][j] <= 1.

Solution:

  • Method 1: dfs AC 16.04%
    • We check all nodes whose value is 0, we try to change this value from 0 to 1 and record the max area could be reach.
      class Solution {
        private int height, width;
        private int res = 0;      
        public int largestIsland(int[][] grid) {
            if(grid == null || grid.length == 0 || grid[0].length == 0) return 0;
            height = grid.length;
            width = grid[0].length;
            for(int i = 0; i < height; i++){
                for(int j = 0; j < width; j++){
                    if(grid[i][j] == 0){ //Assume we change the current node from 0 to 1
                        res = Math.max(dfs(grid, i, j, new boolean[height][width]), res);
                    }
                }
            }
            return res == 0 ? height * width: res;
        }
        private int dfs(int[][] grid, int r, int c, boolean[][] visited){
            int cur = 1;
            int tx = 0, ty = 0;
            visited[r][c] = true;
            for(int d = 0; d < 4; d++){
                tx = r + dir[d][0];
                ty = c + dir[d][1];
                if(tx >= 0 && tx < height && ty >= 0 && ty < width && grid[tx][ty] == 1 && !visited[tx][ty]){
                    cur += dfs(grid, tx, ty, visited);
                }
            }
            return cur;
        }
      }