#include #include #include #include #include #include using namespace std; struct Point { int row, col; bool operator==(const Point& other) const { return row == other.row && col == other.col; } }; constexpr int R = 9, C = 15, INF = 1000000; constexpr int FIRE_DELAY = 4; using Times = array, R>; const array city = { "...............", "...##....##....", "...##....##....", "...............", "S.....##......E", "......##.......", "...##....##....", "...##....##....", "...............", }; const Point start{4, 0}, exitPoint{4, 14}; const Point directions[] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; bool passable(Point p) { return p.row >= 0 && p.row < R && p.col >= 0 && p.col < C && city[p.row][p.col] != '#'; } // The same BFS finds arrival times for fire and for the rescue vehicle. Times arrivalTimes(const vector& sources, int delay, const Times* fire = nullptr, array, R>* parent = nullptr) { Times time; for (auto& row : time) row.fill(INF); queue pending; for (Point source : sources) { if (fire && (*fire)[source.row][source.col] == 0) continue; time[source.row][source.col] = 0; pending.push(source); } while (!pending.empty()) { Point u = pending.front(); pending.pop(); for (Point offset : directions) { Point v{u.row + offset.row, u.col + offset.col}; if (!passable(v) || time[v.row][v.col] != INF) continue; int nextTime = time[u.row][u.col] + delay; // Enter only if the fire has not reached this cell. if (fire && nextTime >= (*fire)[v.row][v.col]) continue; time[v.row][v.col] = nextTime; if (parent) (*parent)[v.row][v.col] = u; pending.push(v); } } return time; } int main(int argc, char** argv) { vector fires{{0, 7}}; if (argc > 1 && string(argv[1]) == "--second-fire") fires.push_back({4, 3}); Times fire = arrivalTimes(fires, FIRE_DELAY); array, R> parent{}; Times rescue = arrivalTimes({start}, 1, &fire, &parent); int eta = rescue[exitPoint.row][exitPoint.col]; if (eta == INF) { cout << "No safe route\n"; return 0; } vector path; for (Point p = exitPoint; !(p == start); p = parent[p.row][p.col]) path.push_back(p); path.push_back(start); reverse(path.begin(), path.end()); cout << "Safe arrival: " << eta << " min\n"; auto map = city; for (Point p : path) if (map[p.row][p.col] == '.') map[p.row][p.col] = '*'; for (Point p : fires) map[p.row][p.col] = 'F'; for (const auto& row : map) cout << row << '\n'; }