Welcome to Subscribe On Youtube
Formatted question description: https://leetcode.ca/all/749.html
749. Contain Virus
Level
Hard
Description
A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as a 2-D array of cells, where 0
represents uninfected cells, and 1
represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region – the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night. There will never be a tie.
Can you save the day? If so, what is the number of walls required? If not, and the world becomes fully infected, return the number of walls used.
Example 1:
Input: grid =
[[0,1,0,0,0,0,0,1],
[0,1,0,0,0,0,0,1],
[0,0,0,0,0,0,0,1],
[0,0,0,0,0,0,0,0]]
Output: 10
Explanation:
There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
[[0,1,0,0,0,0,1,1],
[0,1,0,0,0,0,1,1],
[0,0,0,0,0,0,1,1],
[0,0,0,0,0,0,0,1]]
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
Example 2:
Input: grid =
[[1,1,1],
[1,0,1],
[1,1,1]]
Output: 4
Explanation: Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
Example 3:
Input: grid =
[[1,1,1,0,0,0,0,0,0],
[1,0,1,0,1,1,1,1,1],
[1,1,1,0,0,0,0,0,0]]
Output: 13
Explanation: The region on the left only builds two new walls.
Note:
- The number of rows and columns of grid will each be in the range
[1, 50]
. - Each
grid[i][j]
will be either0
or1
. - Throughout the described process, there is always a contiguous viral region that will infect strictly more uncontaminated squares in the next round.
Solution
Simulate the process. Each time a cell with value 1 is met, do breadth first search on the cell to calculate the area’s perimeter and the number of uncontaminated cells that will be affected by the area. Find the area that will affect the maximum number of uncontaminated cells and install walls around the area. The number of walls used equals the area’s perimeter. Also, replace the values in the area with another number, such as 2. In the other areas, the virus spreads to all neighboring cells, so update the grid’s value. Repeat the process until all contaminated areas are blocked or no more uncontaminated cells remain. Finally, return the total number of walls used.
-
class Solution { public int containVirus(int[][] grid) { int walls = 0; int rows = grid.length, columns = grid[0].length; boolean flag = true; while (flag) { flag = false; int maxArea = 0; int maxIndex = -1; int index = 0; List<int[]> startCells = new ArrayList<int[]>(); List<Integer> perimeters = new ArrayList<Integer>(); boolean[][] visited = new boolean[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (grid[i][j] == 1 && !visited[i][j]) { flag = true; int[] perimeterArea = breadthFirstSearch(grid, i, j, visited); int perimeter = perimeterArea[0], area = perimeterArea[1]; if (area > maxArea) { maxArea = area; maxIndex = index; } startCells.add(new int[]{i, j}); perimeters.add(perimeter); index++; } } } if (maxIndex < 0) break; walls += perimeters.get(maxIndex); updateCellValues(grid, startCells.get(maxIndex)); List<int[]> affectedCells = new ArrayList<int[]>(); int size = perimeters.size(); for (int i = 0; i < size; i++) { if (i != maxIndex) spread(grid, startCells.get(i), affectedCells); } for (int[] cell : affectedCells) grid[cell[0]][cell[1]] = 1; } return walls; } public int[] breadthFirstSearch(int[][] grid, int startRow, int startColumn, boolean[][] visited) { int perimeter = 0; Set<String> set = new HashSet<String>(); int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; int rows = grid.length, columns = grid[0].length; visited[startRow][startColumn] = true; Queue<int[]> queue = new LinkedList<int[]>(); queue.offer(new int[]{startRow, startColumn}); while (!queue.isEmpty()) { int[] cell = queue.poll(); int row = cell[0], column = cell[1]; for (int[] direction : directions) { int newRow = row + direction[0], newColumn = column + direction[1]; if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns) { if (grid[newRow][newColumn] == 0) { perimeter++; set.add(Arrays.toString(new int[]{newRow, newColumn})); } else if (grid[newRow][newColumn] == 1 && !visited[newRow][newColumn]) { visited[newRow][newColumn] = true; queue.offer(new int[]{newRow, newColumn}); } } } } return new int[]{perimeter, set.size()}; } public void updateCellValues(int[][] grid, int[] startCell) { int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; int rows = grid.length, columns = grid[0].length; Queue<int[]> queue = new LinkedList<int[]>(); queue.offer(startCell); while (!queue.isEmpty()) { int[] cell = queue.poll(); int row = cell[0], column = cell[1]; grid[row][column] = -1; for (int[] direction : directions) { int newRow = row + direction[0], newColumn = column + direction[1]; if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns && grid[newRow][newColumn] == 1) { grid[newRow][newColumn] = 2; queue.offer(new int[]{newRow, newColumn}); } } } } public void spread(int[][] grid, int[] startCell, List<int[]> affectedCells) { int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; int rows = grid.length, columns = grid[0].length; boolean[][] visited = new boolean[rows][columns]; visited[startCell[0]][startCell[1]] = true; Queue<int[]> queue = new LinkedList<int[]>(); queue.offer(startCell); while (!queue.isEmpty()) { int[] cell = queue.poll(); int row = cell[0], column = cell[1]; for (int[] direction : directions) { int newRow = row + direction[0], newColumn = column + direction[1]; if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns) { if (grid[newRow][newColumn] == 0) affectedCells.add(new int[]{newRow, newColumn}); else if (grid[newRow][newColumn] == 1 && !visited[newRow][newColumn]) { visited[newRow][newColumn] = true; queue.offer(new int[]{newRow, newColumn}); } } } } } }
-
// OJ: https://leetcode.com/problems/contain-virus/ // Time: O() // Space: O() class UnionFind { vector<int> id; public: UnionFind(int n) : id(n) { iota(begin(id), end(id), 0); } int find(int a) { return id[a] == a ? a : (id[a] = find(id[a])); } void connect(int a, int b) { id[find(a)] = find(b); } bool connected(int a, int b) { return find(a) == find(b); } }; class Solution { public: int containVirus(vector<vector<int>>& A) { int M = A.size(), N = A[0].size(), dirs[4][2] = { {0,1},{0,-1},{1,0},{-1,0} }, ans = 0; auto getKey = [&](int x, int y) { return x * N + y; }; UnionFind uf(M * N); auto getState = [&](int x, int y) { int k = uf.find(getKey(x, y)); return A[k / N][k % N]; }; while (true) { vector<int> cnt(M * N); // count of new infection for (int i = 0; i < M; ++i) { // connect infected components for (int j = 0; j < N; ++j) { if (A[i][j] != 1) continue; for (auto &[dx, dy] : dirs) { int x = i + dx, y = j + dy; if (x < 0 || x >= M || y < 0 || y >= N || A[x][y] != 1) continue; uf.connect(getKey(i, j), getKey(x, y)); } } } for (int i = 0; i < M; ++i) { // get the greatest infection region for (int j = 0; j < N; ++j) { if (getState(i, j) != 0) continue; // for each uninfected cell, check which infected regions can infect it. vector<int> infect; for (auto &[dx, dy] : dirs) { int x = i + dx, y = j + dy; if (x < 0 || x >= M || y < 0 || y >= N || A[x][y] != 1) continue; infect.push_back(uf.find(getKey(x, y))); } sort(begin(infect), end(infect)); infect.erase(unique(begin(infect), end(infect)), end(infect)); for (int k : infect) cnt[k]++; } } int maxInfect = -1; for (int i = 0; i < M * N; ++i) { int x = i / N, y = i % N; if (A[x][y] == 1 && (maxInfect == -1 || cnt[uf.find(i)] > cnt[maxInfect])) maxInfect = uf.find(i); } if (maxInfect == -1) break; for (int i = 0; i < M; ++i) { // build walls for (int j = 0; j < N; ++j) { if (uf.find(getKey(i, j)) != maxInfect) continue; // Only visit the cells in the maxInfect region A[i][j] = 2; // lock this region for (auto &[dx, dy] : dirs) { int x = i + dx, y = j + dy; if (x < 0 || x >= M || y < 0 || y >= N || A[x][y] != 0) continue; ++ans; } } } for (int i = 0; i < M; ++i) { // infect new regions for (int j = 0; j < N; ++j) { if (A[i][j] != 0) continue; // For each uninfected cells, test if it should be infected. for (auto &[dx, dy] : dirs) { int x = i + dx, y = j + dy; if (x < 0 || x >= M || y < 0 || y >= N || A[x][y] != 1) continue; uf.connect(getKey(i, j), getKey(x, y)); // connect this uninfected region with the infected region } } } for (int i = 0; i < M; ++i) { for (int j = 0; j < N; ++j) { if (A[i][j] == 0 && getState(i, j) == 1) A[i][j] = 1; // If this cell itself is not infected, but it should be, mark it as infected } } } return ans; } };
-
class Solution: def containVirus(self, isInfected: List[List[int]]) -> int: def dfs(i, j): vis[i][j] = True areas[-1].append((i, j)) for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]: x, y = i + a, j + b if 0 <= x < m and 0 <= y < n: if isInfected[x][y] == 1 and not vis[x][y]: dfs(x, y) elif isInfected[x][y] == 0: c[-1] += 1 boundaries[-1].add((x, y)) m, n = len(isInfected), len(isInfected[0]) ans = 0 while 1: vis = [[False] * n for _ in range(m)] areas = [] c = [] boundaries = [] for i, row in enumerate(isInfected): for j, v in enumerate(row): if v == 1 and not vis[i][j]: areas.append([]) boundaries.append(set()) c.append(0) dfs(i, j) if not areas: break idx = boundaries.index(max(boundaries, key=len)) ans += c[idx] for k, area in enumerate(areas): if k == idx: for i, j in area: isInfected[i][j] = -1 else: for i, j in area: for a, b in [[0, -1], [0, 1], [-1, 0], [1, 0]]: x, y = i + a, j + b if 0 <= x < m and 0 <= y < n and isInfected[x][y] == 0: isInfected[x][y] = 1 return ans
-
func containVirus(isInfected [][]int) int { m, n := len(isInfected), len(isInfected[0]) ans := 0 dirs := []int{-1, 0, 1, 0, -1} max := func(boundaries []map[int]bool) int { idx := 0 mx := len(boundaries[0]) for i, v := range boundaries { t := len(v) if mx < t { mx = t idx = i } } return idx } for { vis := make([][]bool, m) for i := range vis { vis[i] = make([]bool, n) } areas := []map[int]bool{} boundaries := []map[int]bool{} c := []int{} var dfs func(i, j int) dfs = func(i, j int) { vis[i][j] = true idx := len(areas) - 1 areas[idx][i*n+j] = true for k := 0; k < 4; k++ { x, y := i+dirs[k], j+dirs[k+1] if x >= 0 && x < m && y >= 0 && y < n { if isInfected[x][y] == 1 && !vis[x][y] { dfs(x, y) } else if isInfected[x][y] == 0 { c[idx]++ boundaries[idx][x*n+y] = true } } } } for i, row := range isInfected { for j, v := range row { if v == 1 && !vis[i][j] { areas = append(areas, map[int]bool{}) boundaries = append(boundaries, map[int]bool{}) c = append(c, 0) dfs(i, j) } } } if len(areas) == 0 { break } idx := max(boundaries) ans += c[idx] for t, area := range areas { if t == idx { for v := range area { i, j := v/n, v%n isInfected[i][j] = -1 } } else { for v := range area { i, j := v/n, v%n for k := 0; k < 4; k++ { x, y := i+dirs[k], j+dirs[k+1] if x >= 0 && x < m && y >= 0 && y < n && isInfected[x][y] == 0 { isInfected[x][y] = 1 } } } } } } return ans }