Branch data Line data Source code
1 : : #include <iostream>
2 : : #include <fstream>
3 : : #include <vector>
4 : : #include <unordered_map>
5 : : #include <string>
6 : :
7 : : using namespace std;
8 : :
9 : : static const unordered_map<char, pair<int, int>> deltas = {{'<', {-1, 0}}, {'>', {1, 0}}, {'^', {0, -1}}, {'v', {0, 1}}};
10 : :
11 : : vector<string> grid;
12 : : pair<int, int> robot;
13 : : int gpsSum = 0;
14 : :
15 : 13903 : bool moveBox(const pair<int, int>& box, const pair<int, int>& delta, bool simulate = false) {
16 : 20477 : auto attemptMove = [&delta, &simulate, &box](const pair<int, int>& p) {
17 [ + + + + : 20477 : if (grid[p.second][p.first] == '.' || (grid[p.second][p.first] == '[' || grid[p.second][p.first] == ']') && moveBox(p, delta, simulate)) {
+ + + + +
+ ]
18 [ + + ]: 18375 : if (!simulate) {
19 [ + + ]: 6760 : swap(grid[p.second][p.first], grid[box.second][delta.second ? p.first : box.first]);
20 [ + + ]: 6760 : if(grid[p.second][p.first] == '[') {
21 : 3380 : gpsSum += 100 * delta.second + delta.first;
22 : : }
23 : : }
24 : 18375 : return true;
25 : : }
26 : 2102 : return false;
27 : 13903 : };
28 : :
29 [ + + ]: 13903 : if (delta.second) { // vertical move
30 : 7883 : pair<int, int> newBoxR = {box.first + delta.first + (grid[box.second][box.first] == '['), box.second + delta.second};
31 : 7883 : pair<int, int> newBoxL = {box.first + delta.first - (grid[box.second][box.first] != '['), box.second + delta.second};
32 [ + + + + ]: 7883 : return attemptMove(newBoxL) && attemptMove(newBoxR);
33 : : }
34 : 6020 : return attemptMove({box.first + delta.first, box.second + delta.second}); // horizontal move
35 : : }
36 : :
37 : 2 : int main() {
38 : 2 : ifstream input("input.txt");
39 [ + + ]: 2 : if (!input) {
40 : 1 : cerr << "Error: input.txt not found" << endl;
41 : 1 : return 1;
42 : : }
43 : :
44 [ + - + + : 51 : for (string line; getline(input, line) && !line.empty(); grid.push_back(std::move(line))) {
+ + ]
45 [ + + ]: 2550 : for (size_t x = 0; x < line.size(); x += 2) {
46 [ + + + + : 7500 : line.replace(x, 1, (line[x] == 'O') ? (gpsSum += 100 * grid.size() + x, "[]") : (line[x] == '@') ? (robot = {x, (int)grid.size()}, "@.") : string(2, line[x]));
+ + + + +
+ ]
47 : : }
48 : 1 : }
49 : :
50 [ + + ]: 21 : for (string line; getline(input, line);) {
51 [ + + ]: 20020 : for (char move : line) {
52 : 20000 : auto [dx, dy] = deltas.at(move);
53 : 20000 : pair<int, int> newRobot = {robot.first + dx, robot.second + dy};
54 : :
55 : 20000 : char &target = grid[newRobot.second][newRobot.first];
56 [ + + + + : 20000 : if ((target == '[' || target == ']') ? moveBox(newRobot, {dx, dy}, true) && moveBox(newRobot, {dx, dy}) : target == '.') {
+ + + - +
+ ]
57 : 18163 : swap(target, grid[robot.second][robot.first]);
58 : 18163 : robot = newRobot;
59 : : }
60 : : }
61 : 1 : }
62 : :
63 : 1 : cout << gpsSum << endl;
64 [ + + ]: 3 : }
|