advent-of-code/2023/3/main-2.cpp

59 lines
1.1 KiB
C++
Raw Normal View History

2023-12-02 22:48:41 -08:00
#include <bits/stdc++.h>
using namespace std;
inline bool isDigit(char ch) {
return ch >= '0' && ch <= '9';
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
vector<string> lines;
2023-12-03 16:15:40 -08:00
string line;
while (getline(cin, line) && !line.empty()) {
2023-12-02 22:48:41 -08:00
lines.push_back(line);
2023-12-03 16:15:40 -08:00
}
2023-12-02 22:48:41 -08:00
int ret = 0;
for (int r = 0; r < lines.size(); r++) {
auto& line = lines[r];
int cend = line.size();
for (int c = 0; c < cend; c++) {
char ch = line[c];
if (ch != '*')
continue;
vector<int> rs = {r}, cs = {c};
int p = 1;
int n = 0;
2023-12-02 23:39:35 -08:00
for (int rr = r - 1; rr <= r + 1; rr++) {
if (rr < 0 || rr == lines.size())
continue;
for (int cc = c - 1; cc <= c + 1; cc++) {
if (cc < 0 || cc == cend)
continue;
2023-12-02 22:48:41 -08:00
auto& lo = lines[rr];
if (isDigit(lo[cc])) {
int ci = cc, cf = cc;
while (ci > 0 && isDigit(lo[ci - 1]))
ci--;
while (cf < cend - 1 && isDigit(lo[cf + 1]))
cf++;
p *= stoi(lo.substr(ci, cf - ci + 1));
for (int i = ci; i <= cf; i++)
lo[i] = '.';
if (++n > 2)
goto rrccend;
}
}
}
rrccend:
if (n == 2)
ret += p;
}
}
cout << ret << '\n';
}