Concise c++ solution with BFS, 12ms
\nint containVirus(vector<vector<int>>& g) {\n    int res = 0, c = 1; // c increments for visited cells\n\n    while (true) {\n        // tuple components: wall
```\nint containVirus(vector<vector<int>>& g) {\n    int res = 0, c = 1; // c increments for visited cells\n\n    while (true) {\n        // tuple components: walls, inside coords with value c, border coords with value 0\n        vector<tuple<int, vector<pair<int, int>>, set<pair<int, int>>>> areas;\n        int mx = 0, idx;\n\n        for (int i = 0; i < g.size(); i++) {\n            for (int j = 0; j < g[0].size(); j++) {\n                if (g[i][j] == c) {\n                    areas.resize(areas.size() + 1); // found a new area\n\n                    int &walls = get<0>(areas.back());\n                    auto &inside = get<1>(areas.back());\n                    auto &border = get<2>(areas.back());\n\n                    g[i][j] = c + 1; // mark as visited\n                    inside.emplace_back(i, j);\n\n                    queue<pair<int, int>> q;\n                    q.emplace(i, j);\n\n                    while (!q.empty()) {\n                        int x, y;\n                        tie(x, y) = q.front();\n                        q.pop();\n\n                        for_4neighbors(g, x, y, [&](int a, int b) {\n                            if (g[a][b] == c) {\n                                q.emplace(a, b);\n                                g[a][b] = c + 1; // mark as visited\n                                inside.emplace_back(a, b);\n                            } else if (g[a][b] == 0) {\n                                border.emplace(a, b);\n                                walls++;\n                            }\n                        });\n                    }\n\n                    if (border.size() > mx) {\n                        mx = border.size();\n                        idx = areas.size() - 1;\n                    }\n                }\n            }\n        }\n\n        if (mx == 0) break;\n        c++; // all visited viruses are back\n\n        for (auto &p : get<1>(areas[idx]))\n            g[p.first][p.second] = -1; // mark as dead\n        get<2>(areas[idx]).clear(); // dead viruses no longer spread\n\n        for (auto &a : areas)\n            for (auto &p : get<2>(a))\n                g[p.first][p.second] = c; // mark as contaminated\n\n        res += get<0>(areas[idx]);\n    }\n\n    return res;\n}\n```\n\nWith a helper defined:\n```\ntemplate<typename Ctnr, typename Func>\ninline void for_4neighbors(const Ctnr &ctnr, int row, int col, Func func) {\n    if (row - 1 >= 0)\n        func(row - 1, col);\n    if (row + 1 < ctnr.size())\n        func(row + 1, col);\n    if (col - 1 >= 0)\n        func(row, col - 1);\n    if (col + 1 < ctnr[0].size())\n        func(row, col + 1);\n}\n```
[]