Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <vector>
- using tree_t = std::vector<std::string>;
- struct pt {
- size_t x, y;
- };
- bool valid(const tree_t& tree, const pt p) {
- if (p.y >= tree.size()) return false;
- if (p.x >= tree[p.y].size()) return false;
- return true;
- }
- pt go_left(const pt p, size_t i) { return {p.x - i, p.y + i}; }
- pt go_right(const pt p, size_t i) { return {p.x + i, p.y + i}; }
- char at(const tree_t& tree, const pt p) { return tree[p.y][p.x]; }
- bool has_left_child(const tree_t& tree, const pt p) {
- return valid(tree, go_left(p, 1)) && at(tree, go_left(p, 1)) == '/' &&
- valid(tree, go_left(p, 2));
- }
- bool has_right_child(const tree_t& tree, const pt p) {
- return valid(tree, go_right(p, 1)) && at(tree, go_right(p, 1)) == '\\' &&
- valid(tree, go_right(p, 2));
- }
- pt root(const tree_t& tree) {
- size_t root = -1;
- for (size_t i = 0; i < tree.front().size(); i++) {
- if (tree.front()[i] != ' ') {
- root = i;
- }
- }
- return {root, 0};
- }
- void dfs(const tree_t& tree, pt p, std::string& my_stack,
- std::string& solution) {
- bool has_child = false;
- my_stack += at(tree, p);
- if (has_left_child(tree, p)) {
- has_child = true;
- dfs(tree, go_left(p, 2), my_stack, solution);
- }
- if (has_right_child(tree, p)) {
- has_child = true;
- dfs(tree, go_right(p, 2), my_stack, solution);
- }
- if (!has_child) {
- if (solution.back() == ']') {
- solution += ", ";
- }
- solution += "[";
- for (char c : my_stack) {
- solution += c;
- solution += ", ";
- }
- solution.pop_back();
- solution.back() = ']';
- }
- my_stack.pop_back();
- }
- std::string solution(const tree_t& tree) {
- pt r = root(tree);
- std::string my_stack = "";
- std::string solution = "[";
- dfs(tree, r, my_stack, solution);
- solution += "]";
- return solution;
- }
- int main() {
- // clang-format off
- const tree_t tree = {
- " 1",
- " / \\",
- " 2 3",
- " / \\",
- " 4 5"
- };
- // clang-format on
- std::cout << solution(tree) << std::endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement