Advertisement
Guest User

Untitled

a guest
Apr 6th, 2020
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4.  
  5. void findStartCoordinates(int start_x, int start_y,
  6.                           std::vector<std::vector<char>> maze) {
  7.     for (int i = 0; i < maze.size(); i++) {
  8.         for (int j = 0; j < maze[0].size(); j++) {
  9.             if (maze[i][j] == 'A') {
  10.                 start_x = i;
  11.                 start_y = j;
  12.                 return;
  13.             }
  14.         }
  15.     }
  16. }
  17.  
  18. bool solveMaze(int x, int y, std::vector<std::vector<char>>& maze) {
  19.     if (maze[x][y] == 'B') return true;
  20.     if (x < 0 || x >= maze.size() ||
  21.         y < 0 || y >= maze.size() ||
  22.         maze[x][y] != ' ') return false;
  23.    
  24.     maze[x][y] = '.';
  25.  
  26.     if (solveMaze(x, y - 1, maze)) return true;
  27.     if (solveMaze(x + 1, y, maze)) return true;
  28.     if (solveMaze(x, y + 1, maze)) return true;
  29.     if (solveMaze(x - 1, y, maze)) return true;
  30.  
  31.     maze[x][y] = ' ';
  32.     return false;
  33. }
  34.  
  35. void printMaze(std::vector<std::vector<char>> maze) {
  36.     for (auto line : maze) {
  37.         for (auto obs : line) {
  38.             std::cout << obs;
  39.         }
  40.         std::cout << '\n';
  41.     }
  42. }
  43.  
  44. int main() {
  45.     std::ifstream file("labirynt.txt");
  46.     std::vector<std::vector<char>> maze;
  47.     for (std::string line;
  48.          std::getline(file, line);
  49.          maze.emplace_back(line.begin(), line.end()));
  50.    
  51.     int start_x, start_y;
  52.     findStartCoordinates(start_x, start_y, maze);
  53.    
  54.     maze[start_x][start_y] = ' ';
  55.     solveMaze(start_x, start_y, maze);
  56.     maze[start_x][start_y] = 'A';
  57.    
  58.     printMaze(maze);
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement