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

63 lines
1.2 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;
do {
string line;
getline(cin, line);
if (line.empty())
break;
lines.push_back(line);
} while (!cin.eof());
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;
vector<int> rs = {r}, cs = {c};
if (r > 0) {
rs.push_back(r - 1);
if (r < lines.size() - 1)
rs.push_back(r + 1);
}
if (c > 0) {
cs.push_back(c - 1);
if (c < cend - 1)
cs.push_back(c + 1);
}
for (int rr : rs) {
for (int cc : cs) {
if (r == 0 && c == 0)
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';
}