Advertisement
Guest User

Untitled

a guest
Jan 30th, 2018
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.62 KB | None | 0 0
  1. static int WIDTH, HEIGHT;
  2. static std::string memo_space; // take note of the visited locations to avoid revisiting them
  3.  
  4. struct Point {
  5.     int x, y;
  6.     friend bool operator==(const Point &p1, const Point &p2);
  7. };
  8.  
  9. bool operator==(const Point &p1, const Point &p2) {
  10.     return p1.x == p2.x && p1.y == p2.y;
  11. }
  12.  
  13. int idx(const Point &p) {
  14.     return p.y * WIDTH + p.x;
  15. }
  16.  
  17. bool canTravel(const Point &start, const Point &end, char c) {
  18.     if (start == end) return true; // base case: the start == the destination
  19.     memo_space[idx(start)] = 'x' // add current location to the list of visited locations
  20.  
  21.     /*
  22.     format:
  23.  
  24.     const auto &next_location = avoid out of bounds error &&
  25.         next location has the same digit as the current one &&
  26.         recursively check whether the next location can reach the destination
  27.  
  28.     */
  29.  
  30.     const auto &right = start.x < WIDTH - 1 &&
  31.         memo_space[idx({ start.x + 1, start.y })] == 'o' &&
  32.         canTravel({ start.x + 1, start.y }, end, c);
  33.  
  34.     if (right) return true;
  35.  
  36.     const auto &left = start.x > 0 &&
  37.         memo_space[idx({ start.x - 1, start.y })] == 'o' &&
  38.         canTravel({ start.x - 1, start.y }, end, c);
  39.  
  40.     if (left) return true;
  41.  
  42.     const auto &down = start.y < HEIGHT - 1 &&
  43.         memo_space[idx({ start.x, start.y + 1 })] == 'o' &&
  44.         canTravel({ start.x, start.y + 1 }, end, c);
  45.  
  46.     if (down) return true;
  47.  
  48.     const auto &up = start.y > 0 &&
  49.         memo_space[idx({ start.x, start.y - 1 })] == 'o' &&
  50.         canTravel({ start.x, start.y - 1 }, end, c);
  51.  
  52.     if (up) return true;
  53.  
  54.     return false;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement