|
| 1 | +/** |
| 2 | + * @param {number[][]} grid |
| 3 | + * @return {number} |
| 4 | + */ |
| 5 | +const containVirus = function (grid) { |
| 6 | + let ans = 0 |
| 7 | + while (true) { |
| 8 | + const walls = model(grid) |
| 9 | + if (walls === 0) break |
| 10 | + ans += walls |
| 11 | + } |
| 12 | + return ans |
| 13 | + function model(grid) { |
| 14 | + const m = grid.length, |
| 15 | + n = grid[0].length |
| 16 | + const virus = [], |
| 17 | + toInfect = [] |
| 18 | + const visited = Array.from({ length: m }, () => Array(n).fill(0)) |
| 19 | + const walls = [] |
| 20 | + for (let i = 0; i < m; i++) { |
| 21 | + for (let j = 0; j < n; j++) { |
| 22 | + if (grid[i][j] === 1 && visited[i][j] === 0) { |
| 23 | + virus.push(new Set()) |
| 24 | + toInfect.push(new Set()) |
| 25 | + walls.push([0]) |
| 26 | + dfs( |
| 27 | + grid, |
| 28 | + visited, |
| 29 | + virus[virus.length - 1], |
| 30 | + toInfect[toInfect.length - 1], |
| 31 | + walls[walls.length - 1], |
| 32 | + i, |
| 33 | + j |
| 34 | + ) |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + let maxArea = 0, |
| 39 | + idx = -1 |
| 40 | + for (let i = 0; i < toInfect.length; i++) { |
| 41 | + if (toInfect[i].size > maxArea) { |
| 42 | + maxArea = toInfect[i].size |
| 43 | + idx = i |
| 44 | + } |
| 45 | + } |
| 46 | + if (idx === -1) return 0 |
| 47 | + for (let i = 0; i < toInfect.length; i++) { |
| 48 | + if (i !== idx) { |
| 49 | + for (let key of toInfect[i]) grid[(key / n) >> 0][key % n] = 1 |
| 50 | + } else { |
| 51 | + for (let key of virus[i]) grid[(key / n) >> 0][key % n] = -1 |
| 52 | + } |
| 53 | + } |
| 54 | + return walls[idx][0] |
| 55 | + } |
| 56 | + function dfs(grid, visited, virus, toInfect, wall, row, col) { |
| 57 | + const m = grid.length, |
| 58 | + n = grid[0].length |
| 59 | + if (row < 0 || row >= m || col < 0 || col >= n || visited[row][col] === 1) |
| 60 | + return |
| 61 | + if (grid[row][col] === 1) { |
| 62 | + visited[row][col] = 1 |
| 63 | + virus.add(row * n + col) |
| 64 | + const dir = [0, -1, 0, 1, 0] |
| 65 | + for (let i = 0; i < 4; i++) |
| 66 | + dfs( |
| 67 | + grid, |
| 68 | + visited, |
| 69 | + virus, |
| 70 | + toInfect, |
| 71 | + wall, |
| 72 | + row + dir[i], |
| 73 | + col + dir[i + 1] |
| 74 | + ) |
| 75 | + } else if (grid[row][col] === 0) { |
| 76 | + wall[0]++ |
| 77 | + toInfect.add(row * n + col) |
| 78 | + } |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +// another |
| 83 | + |
1 | 84 | /**
|
2 | 85 | * @param {number[][]} grid
|
3 | 86 | * @return {number}
|
|
0 commit comments