leetcode
leetcode 2651 ~ 2700
隔离病毒

隔离病毒

难度:

标签:

题目描述

A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.

The world is modeled as an m x n binary grid isInfected, where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 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 (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There will never be a tie.

Return the number of walls used to quarantine all the infected regions. If the world will become fully infected, return the number of walls used.

 

Example 1:

Input: isInfected = [[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:

On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.

Example 2:

Input: isInfected = [[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: isInfected = [[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.

 

Constraints:

  • m == isInfected.length
  • n == isInfected[i].length
  • 1 <= m, n <= 50
  • isInfected[i][j] is either 0 or 1.
  • There is always a contiguous viral region throughout the described process that will infect strictly more uncontaminated squares in the next round.

代码结果

运行时间: 53 ms, 内存: 16.6 MB


解释

方法:

这个题解使用了BFS和贪心算法。主要思路是每一轮选择一个感染区域进行隔离,选择的标准是该区域周围的未感染区域数量最多。具体做法是:每一轮对所有感染区域进行BFS遍历,计算每个感染区域周围的未感染区域数量,同时将感染区域的坐标标记为负数,不同的感染区域用不同的负数标记。然后选择未感染区域数量最多的感染区域,将其周围的未感染区域隔离,并将答案加上隔离区域的数量。然后将所有感染区域的标记还原,未被隔离的感染区域向周围扩散。重复以上过程直到没有感染区域。

时间复杂度:

O(mn^2 * log(mn))

空间复杂度:

O(mn)

代码细节讲解

🦆
在题解中提到使用BFS和贪心算法,贪心算法在这个问题中的具体应用是什么?
在这个问题中,贪心算法的应用体现在每一轮选择进行隔离的感染区域时采用的策略上。具体来说,选择隔离的感染区域基于每个区域周围未感染区域的数量,优先隔离那些周围有最多未感染区域的感染源。这种策略是基于一种贪心思想——假定通过优先阻断最大潜在扩散的感染源可以最有效地控制病毒的整体扩散。
🦆
如何保证每轮选择的感染区域确实是对未感染区域威胁最大的,而不是仅就当前已知条件最大?
题解中的算法实际上是基于当前已知情况进行决策的,即每一轮基于当前的感染状况和未感染区域的分布来选择隔离区域。这种方法并不能保证长期来看是最优的,因为它不考虑未来可能的变化,如病毒通过其他路径的扩散。然而,由于病毒扩散的复杂性和不可预测性,使用基于当前信息的贪心策略是一种实际可行且相对有效的近似方法。
🦆
题解中未详细解释为何将感染区域标记为负数以及使用不同的负数标记不同的感染区域的具体原因,这样做的目的是什么?
在题解中,将感染区域标记为不同的负数主要用于区分和跟踪不同的感染区域,并且防止在同一轮的BFS中重复处理同一个区域。这种做法有助于有效管理和识别各个感染源,确保每个感染源都能被正确地计算其周围未感染区域的数目和需要的隔离墙数量。此外,使用负值还能简化将感染状态恢复为正常状态的逻辑,因为只需检查负值即可轻松区分感染区域和非感染区域。

相关问题