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:

  1. The number of rows and columns of grid will each be in the range [1, 50].
  2. Each grid[i][j] will be either 0 or 1.
  3. 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});
                    }
                }
            }
        }
    }
}

All Problems

All Solutions