题目地址:
https://leetcode.com/problems/contain-virus/description/
给定一个 m × n m\times n m×n的二维 01 01 01矩阵 g g g,每个 1 1 1视为病毒, 0 0 0视为空地。每一轮每个病毒会感染其四个方向上的格子,但是我们可以将感染格子最多的 1 1 1连通块用隔板隔离,要用的隔板数量即为其周长(边界上不需要隔板)。题目数据保证每一轮要隔离的连通块是唯一的。问需要的总共隔板数。
模拟题。进行若干轮,每一轮遍历所有的 1 1 1连通块,同时存一下这个连通块的边界长度(即要包围它需要的隔板数),和这个连通块可以感染的空格数(需要用哈希表存以去重),同时更新一下感染的空格数最大可以是多少。遍历完之后,将所有遍历过的点标记为 − 1 -1 −1,同时将新感染的格子标记为 1 1 1,累加隔板数。如此循环,直到无法继续感染新格子为止。代码如下:
#define x first
#define y second
using PII = pair<int, int>;
auto phash = [](const PII& p) { return hash<int>()(p.x) ^ hash<int>()(p.y); };
vector<PII> v;
unordered_set<PII, decltype(phash)> st(0, phash);
int m, n;
class Solution {
public:
int dfs(int x, int y, vector<PII>& v, unordered_set<PII, decltype(phash)>& st,
vector<vector<bool>>& vis, vector<vector<int>>& g) {
static int d[] = {-1, 0, 1, 0, -1};
vis[x][y] = true;
v.push_back({x, y});
int res = 0;
for (int i = 0; i < 4; i++) {
int nx = x + d[i], ny = y + d[i + 1];
if (0 <= nx && nx < m && 0 <= ny && ny < n) {
if (!g[nx][ny])
st.insert({nx, ny}), res++;
else if (g[nx][ny] == 1 && !vis[nx][ny])
res += dfs(nx, ny, v, st, vis, g);
}
}
return res;
}
int find(vector<vector<int>>& g) {
int cnt = 0, res = 0;
vector<PII> ps;
vector<unordered_set<PII, decltype(phash)>> ss;
vector<vector<bool>> vis(m, vector<bool>(n));
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
if (g[i][j] == 1 && !vis[i][j]) {
v.clear(), st.clear();
int t = dfs(i, j, v, st, vis, g);
if (st.size() > cnt) {
cnt = st.size();
res = t;
ps = v;
}
ss.push_back(st);
}
}
for (auto& p : ps) g[p.x][p.y] = -1;
for (auto& s : ss)
if (s.size() != cnt)
for (auto& p : s) g[p.x][p.y] = 1;
return res;
}
int containVirus(vector<vector<int>>& g) {
m = g.size(), n = g[0].size();
int cnt = 0, res = 0;
while (cnt = find(g)) res += cnt;
return res;
}
};
时间复杂度 O ( ( m n ) 2 ) O((mn)^2) O((mn)2),空间 O ( m n ) O(mn) O(mn)。