python
\n\n# Code\n\nclass Solution:\n    def containVirus(self, mat: List[List[int]]) -> int:\n        m, n = len(mat), len(mat[0])\n        DIRECTIONS = [(-1, 0), (1
\n\n# Code\n```\nclass Solution:\n    def containVirus(self, mat: List[List[int]]) -> int:\n        m, n = len(mat), len(mat[0])\n        DIRECTIONS = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n        \n        def dfs(i, j, visited):\n            if not (0 <= i < m and 0 <= j < n) or (i, j) in visited:\n                return set(), 0\n            if mat[i][j] == 2:\n                return set(), 0\n            elif mat[i][j] == 0:\n                return {(i, j)}, 1\n            \n            visited.add((i, j))\n            infected, walls = set(), 0\n            for dx, dy in DIRECTIONS:\n                ni, nj = i + dx, j + dy\n                next_infected, next_walls = dfs(ni, nj, visited)\n                infected |= next_infected\n                walls += next_walls\n            return infected, walls\n        \n        def quarantine(i, j):\n            if 0 <= i < m and 0 <= j < n and mat[i][j] == 1:\n                mat[i][j] = 2\n                for dx, dy in DIRECTIONS:\n                    quarantine(i + dx, j + dy)\n        \n        ans = 0\n        while True:\n            visited, regions = set(), []\n            for i in range(m):\n                for j in range(n):\n                    if mat[i][j] == 1 and (i, j) not in visited:\n                        infected, walls = dfs(i, j, visited)\n                        if infected:\n                            regions.append((infected, walls, (i, j)))\n            \n            if not regions:\n                break\n            \n            regions.sort(key=lambda x: (-len(x[0]), x[1]))\n            max_infected, max_walls, start = regions[0]\n            ans += max_walls\n            quarantine(*start)\n            \n            for region in regions[1:]:\n                for i, j in region[0]:\n                    mat[i][j] = 1\n        \n        return ans\n```
['Python3']