advent-of-code/2024/15/main-2.cpp
2024-12-14 23:09:24 -08:00

118 lines
1.9 KiB
C++

#include <bits/stdc++.h>
using namespace std;
set<pair<int, int>> boxes;
set<pair<int, int>> walls;
inline void incpair(pair<int, int> &a, pair<int, int> b) {
a.first += b.first;
a.second += b.second;
}
inline pair<int, int> addpair(pair<int, int> a, pair<int, int> b) {
incpair(a, b);
return a;
}
bool rec(pair<int, int> pos, pair<int, int> dir, set<pair<int, int>> &acc) {
if (acc.contains(pos)) {
return true;
}
if (walls.contains(pos)) {
return false;
}
if (!boxes.contains(pos)) {
incpair(pos, {0, -1});
if (!boxes.contains(pos)) {
return true;
}
}
acc.insert(pos);
incpair(pos, dir);
bool other;
switch (dir.second) {
case 0:
other = rec(addpair(pos, {0, 1}), dir, acc);
break;
case 1:
pos.second += 1;
default:
other = true;
}
return other && rec(pos, dir, acc);
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
vector<string> grid;
string line;
pair<int, int> robot;
double x = 0;
while (getline(cin, line) && !line.empty()) {
double y = 0;
for (char c : line) {
switch (c) {
case '#':
walls.insert({x, y});
walls.insert({x, y + 1});
break;
case 'O':
boxes.insert({x, y});
break;
case '@':
robot = {x, y};
break;
}
y += 2;
}
x++;
}
while (getline(cin, line) && !line.empty()) {
for (char c : line) {
pair<int, int> dir;
switch (c) {
case '<':
dir = {0, -1};
break;
case '>':
dir = {0, 1};
break;
case '^':
dir = {-1, 0};
break;
case 'v':
dir = {1, 0};
break;
}
set<pair<int, int>> r;
auto first = addpair(robot, dir);
if (!rec(first, dir, r)) {
continue;
}
robot = first;
for (auto box : r) {
boxes.erase(box);
}
for (auto box : r) {
boxes.insert(addpair(box, dir));
}
}
}
int sum = 0;
for (auto box : boxes) {
sum += 100 * box.first + box.second;
}
cout << sum << '\n';
}