827. Making A Large Island

网友投稿 251 2022-12-01

827. Making A Large Island

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: 3Explanation: 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: 4Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 1.

Example 3:

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

Notes:

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

class Solution { int[] dr = new int[]{-1, 0, 1, 0}; int[] dc = new int[]{0, -1, 0, 1}; public int largestIsland(int[][] grid) { int N = grid.length; int ans = 0; boolean 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; ans = Math.max(ans, check(grid, r, c)); grid[r][c] = 0; } return hasZero ? ans : N*N; } public int check(int[][] grid, int r0, int c0) { int N = grid.length; Stack stack = new Stack(); Set seen = new HashSet(); stack.push(r0 * N + c0); seen.add(r0 * N + c0); while (!stack.isEmpty()) { int code = stack.pop(); int r = code / N, c = code % N; for (int k = 0; k < 4; ++k) { int nr = r + dr[k], nc = c + dc[k]; if (!seen.contains(nr * N + nc) && 0 <= nr && nr < N && 0 <= nc && nc < N && grid[nr][nc] == 1) { stack.push(nr * N + nc); seen.add(nr * N + nc); } } } return

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:使用springboot单元测试对weblistener的加载测试
下一篇:14. Longest Common Prefix
相关文章

 发表评论

暂时没有评论,来抢沙发吧~