|
| 1 | +# 最大人工岛 |
| 2 | + |
| 3 | +> 难度:困难 |
| 4 | +> |
| 5 | +> https://leetcode.cn/problems/making-a-large-island/ |
| 6 | +
|
| 7 | +## 题目 |
| 8 | + |
| 9 | +给你一个大小为 `n x n` 二进制矩阵 `grid` 。**最多** 只能将一格 `0` 变成 `1` 。 |
| 10 | + |
| 11 | +返回执行此操作后,`grid` 中最大的岛屿面积是多少? |
| 12 | + |
| 13 | +岛屿 由一组上、下、左、右四个方向相连的 `1` 形成。 |
| 14 | + |
| 15 | +### 示例 |
| 16 | + |
| 17 | +#### 示例 1: |
| 18 | + |
| 19 | +``` |
| 20 | +输入: grid = [[1, 0], [0, 1]] |
| 21 | +输出: 3 |
| 22 | +解释: 将一格0变成1,最终连通两个小岛得到面积为 3 的岛屿。 |
| 23 | +``` |
| 24 | + |
| 25 | +#### 示例 2: |
| 26 | + |
| 27 | +``` |
| 28 | +输入: grid = [[1, 1], [1, 0]] |
| 29 | +输出: 4 |
| 30 | +解释: 将一格0变成1,岛屿的面积扩大为 4。 |
| 31 | +``` |
| 32 | + |
| 33 | +#### 示例 3: |
| 34 | + |
| 35 | +``` |
| 36 | +输入: grid = [[1, 1], [1, 1]] |
| 37 | +输出: 4 |
| 38 | +解释: 没有0可以让我们变成1,面积依然为 4。 |
| 39 | +``` |
| 40 | + |
| 41 | +## 解题 |
| 42 | + |
| 43 | +```ts |
| 44 | +/** |
| 45 | + * 标记岛屿 + 合并 |
| 46 | + * @desc 时间复杂度 O(N²) 空间复杂度 O(N²) |
| 47 | + * @param grid |
| 48 | + * @returns |
| 49 | + */ |
| 50 | +export function largestIsland(grid: number[][]): number { |
| 51 | + const valid = (n: number, x: number, y: number) => x >= 0 && x < n && y >= 0 && y < n |
| 52 | + |
| 53 | + const d = [0, -1, 0, 1, 0] |
| 54 | + const n = grid.length |
| 55 | + let res = 0 |
| 56 | + const tag: number[][] = new Array(n).fill(0).map(() => new Array(n).fill(0)) |
| 57 | + const area = new Map<number, number>() |
| 58 | + for (let i = 0; i < n; i++) { |
| 59 | + for (let j = 0; j < n; j++) { |
| 60 | + if (grid[i][j] === 1 && tag[i][j] === 0) { |
| 61 | + const t = i * n + j + 1 |
| 62 | + area.set(t, dfs(grid, i, j, tag, t)) |
| 63 | + res = Math.max(res, area.get(t)!) |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + for (let i = 0; i < n; i++) { |
| 68 | + for (let j = 0; j < n; j++) { |
| 69 | + if (grid[i][j] === 0) { |
| 70 | + let z = 1 |
| 71 | + const connected = new Set() |
| 72 | + for (let k = 0; k < 4; k++) { |
| 73 | + const x = i + d[k]; const y = j + d[k + 1] |
| 74 | + if (!valid(n, x, y) || tag[x][y] === 0 || connected.has(tag[x][y])) |
| 75 | + continue |
| 76 | + |
| 77 | + z += area.get(tag[x][y])! |
| 78 | + connected.add(tag[x][y]) |
| 79 | + } |
| 80 | + res = Math.max(res, z) |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + return res |
| 85 | + |
| 86 | + function dfs(grid: number[][], x: number, y: number, tag: number[][], t: number) { |
| 87 | + const n = grid.length; let res = 1 |
| 88 | + tag[x][y] = t |
| 89 | + for (let i = 0; i < 4; i++) { |
| 90 | + const x1 = x + d[i]; const y1 = y + d[i + 1] |
| 91 | + if (valid(n, x1, y1) && grid[x1][y1] === 1 && tag[x1][y1] === 0) |
| 92 | + res += dfs(grid, x1, y1, tag, t) |
| 93 | + } |
| 94 | + return res |
| 95 | + } |
| 96 | +} |
| 97 | +``` |
0 commit comments