advent-of-code/2023/3/main-1.cpp
2023-12-03 17:13:16 -08:00

54 lines
1 KiB
C++

#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;
while (!cin.eof()) {
string line;
getline(cin, line);
if (line.empty())
break;
lines.push_back(line);
}
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 == '.' || isDigit(ch))
continue;
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;
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++;
ret += stoi(lo.substr(ci, cf - ci + 1));
for (int i = ci; i <= cf; i++)
lo[i] = '.';
}
}
}
}
}
cout << ret << '\n';
}