Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static int WIDTH, HEIGHT;
- static std::string memo_space; // take note of the visited locations to avoid revisiting them
- struct Point {
- int x, y;
- friend bool operator==(const Point &p1, const Point &p2);
- };
- bool operator==(const Point &p1, const Point &p2) {
- return p1.x == p2.x && p1.y == p2.y;
- }
- int idx(const Point &p) {
- return p.y * WIDTH + p.x;
- }
- bool canTravel(const Point &start, const Point &end, char c) {
- if (start == end) return true; // base case: the start == the destination
- memo_space[idx(start)] = 'x' // add current location to the list of visited locations
- /*
- format:
- const auto &next_location = avoid out of bounds error &&
- next location has the same digit as the current one &&
- recursively check whether the next location can reach the destination
- */
- const auto &right = start.x < WIDTH - 1 &&
- memo_space[idx({ start.x + 1, start.y })] == 'o' &&
- canTravel({ start.x + 1, start.y }, end, c);
- if (right) return true;
- const auto &left = start.x > 0 &&
- memo_space[idx({ start.x - 1, start.y })] == 'o' &&
- canTravel({ start.x - 1, start.y }, end, c);
- if (left) return true;
- const auto &down = start.y < HEIGHT - 1 &&
- memo_space[idx({ start.x, start.y + 1 })] == 'o' &&
- canTravel({ start.x, start.y + 1 }, end, c);
- if (down) return true;
- const auto &up = start.y > 0 &&
- memo_space[idx({ start.x, start.y - 1 })] == 'o' &&
- canTravel({ start.x, start.y - 1 }, end, c);
- if (up) return true;
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement