-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathday_12a.cpp
102 lines (91 loc) · 2.49 KB
/
day_12a.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <algorithm>
#include <fstream>
#include <iostream>
#include <queue>
#include <regex>
#include <stack>
#include <string>
#include <vector>
struct Point {
Point(const int row, const int col, const int parent, const int steps) : row(row), col(col), parent(parent), steps(steps) {}
int row, col, parent, steps;
};
struct PointHash {
std::size_t operator() (const Point& p) {
return p.row * p.col;
}
};
int main(int argc, char * argv[]) {
std::string input = "../input/day_12_input";
if (argc > 1) {
input = argv[1];
}
std::string line;
std::fstream file(input);
std::vector<Point> motions = {
Point(0, -1, 0, 0),
Point(-1, 0, 0, 0),
Point(0, 1, 0, 0),
Point(1, 0, 0, 0)
};
std::vector<std::string> grid;
Point start(0,0,0, 0);
Point end(0,0,0, 0);
while(std::getline(file, line)) {
grid.push_back(line);
auto it = line.find('S');
if (it != std::string::npos) {
start.row = grid.size() - 1;
start.col = it;
start.parent = start.row * grid[0].size() + start.col;
start.steps = 0;
grid[start.row][start.col] = 'a';
}
it = line.find('E');
if (it != std::string::npos) {
end.row = grid.size() - 1;
end.col = it;
end.parent = 0;
end.steps = 0;
grid[end.row][end.col] = 'z';
}
}
// TODO repalce with unordered set
std::vector<std::vector<bool>> visited(
grid.size(),
std::vector<bool>(grid[0].size(), false)
);
// Point current;
bool found = false;
std::queue<Point> q;
q.push(start);
// Make lambda as_const
const auto in_bounds = [&grid](const auto& p) {
return p.row >= 0 && p.col >= 0 && p.row < grid.size() && p.col < grid[0].size();
};
// TODO Add operators for point
while (!q.empty()) {
auto current = q.front();
q.pop();
if (visited[current.row][current.col]) continue;
visited[current.row][current.col] = true;
if (current.row == end.row && current.col == end.col) {
found = true;
std::cout << current.steps << '\n';
break;
}
for (const auto& motion : motions) {
const auto new_point = Point(
current.row + motion.row,
current.col + motion.col,
current.row * grid[0].size() + current.col,
current.steps + 1
);
if (!in_bounds(new_point)) continue;
if (visited[new_point.row][new_point.col]) continue;
if ((grid[current.row][current.col] + 1) < grid[new_point.row][new_point.col]) continue;
q.push(new_point);
}
}
return 0;
}