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.
DFS求解,将数组矩阵中,值为0的地方替换为1,然后求1相邻的个数即可。直接求解的方式如下所示:
class Solution {
public int largestCnt = 1, curLargestCnt = 0;
public int largestIsland(int[][] grid) {
int cnt = 0;
boolean tag = false;
for (int i = 0; i < grid.length; ++ i){
for (int j = 0; j < grid[i].length; ++ j){
curLargestCnt = 0;
if (grid[i][j] == 0){
grid[i][j] = 1;
boolean[][] visited = new boolean[grid.length][grid[i].length];
largestIslandDFS(grid, visited, i, j);
largestCnt = Math.max(largestCnt, curLargestCnt);
grid[i][j] = 0;
}
else if (!tag){
tag = true;
boolean[][] visited = new boolean[grid.length][grid[i].length];
largestIslandDFS(grid, visited, i, j);
largestCnt = Math.max(largestCnt, curLargestCnt);
}
}
}
return largestCnt;
}
public void largestIslandDFS(int[][] grid, boolean[][] visited, int i, int j){
if (i < 0 || i >= grid.length || j < 0 || j >= grid[i].length){
return;
}
if (grid[i][j] != 1 || visited[i][j]){
return;
}
visited[i][j] = true;
curLargestCnt ++;
largestIslandDFS(grid, visited, i, j - 1);
largestIslandDFS(grid, visited, i - 1, j);
largestIslandDFS(grid, visited, i + 1, j);
largestIslandDFS(grid, visited, i, j + 1);
}
}
上述方案有优化的地方,就是将已经访问过的1的位置,替换为与该1相连的1的总数,这样下次访问的时候,直接取值,可以减少原始位置值为1的访问次数,提高效率。