1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| #include <iostream> #include <vector> #include <ostream> #include <sstream> #include <unordered_map> #include <algorithm> #include <cmath> #include <queue> #include <unordered_set> #include <stack> using namespace std;
int BFS(vector<vector<int>> &data) { queue<pair<int, int>> infect; int health = 0;
for (int i = 0; i < data.size(); ++i) { for (int j = 0; j < data[0].size(); ++j) { if (data[i][j] == 1) { infect.emplace(i, j); } else { health++; } } }
if (health == 0 || infect.empty()) { return -1; }
int days = 0;
vector<vector<int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; while (!infect.empty() && health > 0) { auto [i, j] = infect.front(); infect.pop(); days = data[i][j] + 1; for (auto &dir : dirs) { int x = i + dir[0]; int y = j + dir[1]; if (x >= 0 && x < data.size() && y >= 0 && y < data[0].size() && data[x][y] == 0) { health--; data[x][y] = days; infect.emplace(x, y); } } }
return days - 1; }
int main() {
std::string line; std::getline(std::cin, line);
auto N = static_cast<int>(sqrt((line.size()) / 2 + 1)); std::vector<std::vector<int>> data(N, std::vector<int>(N));
int index = 0; for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { data[i][j] = line[index] - '0'; index += 2; } }
cout << BFS(data) << endl;
return 0; }
|
我觉得这里面比较难想的是 days 的计算,是通过积累来做的:
image20250402181435890.png
由于我们不是一路走到黑,而是处理周围的节点,再通过周围的节点处理周围的节点,像一个湖中扔了一颗石头,陷入波纹展开的过程,故而是广度优先搜索。