nearest-exit-from-entrance-in-maze 1.0.0
Nearest Exit from Entrance in Maze
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include <bits/stdc++.h>
2
3using namespace std;
4
6{
7public:
8 int nearestExit(vector<vector<char>>& maze, vector<int>& entrance)
9 {
10 int m = (int)maze.size(), n = (int)maze[0].size();
11
12 vector<vector<bool>> visited(m, vector(n, false)); // each field is not visited
13
14 // x and y as entrance
15 int x = entrance[0], y = entrance[1];
16 visited[x][y] = true; // entrance is visited
17
18 // add neighbors of the entrance to the processing queue
19 queue<pair<int, int>> steps;
20 if (x - 1 >= 0 && maze[x - 1][y] == '.')
21 steps.push({x - 1, y});
22 if (x + 1 < m && maze[x + 1][y] == '.')
23 steps.push({x + 1, y});
24 if (y - 1 >= 0 && maze[x][y - 1] == '.')
25 steps.push({x, y - 1});
26 if (y + 1 < n && maze[x][y + 1] == '.')
27 steps.push({x, y + 1});
28 if (steps.empty())
29 return -1;
30
31 // searching for the nearest exit in each direction
32 int level = 1;
33 while (!steps.empty())
34 {
35 int size = steps.size();
36 for (int i = 0; i < size; ++i)
37 {
38 auto [x, y] = steps.front();
39 steps.pop();
40 // cout << "Current x: " << x << "; current y: " << y << endl;
41
42 if (x == 0 || y == 0 || x == m - 1 || y == n - 1)
43 return level;
44
45 if (x - 1 >= 0 && maze[x - 1][y] == '.' && !(visited[x - 1][y]))
46 {
47 steps.push({x - 1, y});
48 visited[x - 1][y] = true;
49 }
50 if (x + 1 < m && maze[x + 1][y] == '.' && !(visited[x + 1][y]))
51 {
52 steps.push({x + 1, y});
53 visited[x + 1][y] = true;
54 }
55 if (y - 1 >= 0 && maze[x][y - 1] == '.' && !(visited[x][y - 1]))
56 {
57 steps.push({x, y - 1});
58 visited[x][y - 1] = true;
59 }
60 if (y + 1 < n && maze[x][y + 1] == '.' && !(visited[x][y + 1]))
61 {
62 steps.push({x, y + 1});
63 visited[x][y + 1] = true;
64 }
65 }
66 // level is only incremented when whole level is handled
67 level++;
68 }
69 return -1;
70 }
71};
72
73int main()
74{
75 // vector<vector<char>> maze = {{'+','+','.','+'} ,{'.','.','.','+'}, {'+','+','+','.'}};
76 // vector<int> entrance = {1, 2};
77 vector<vector<char>> maze = {{'+','+','+'} ,{'.','.','.'}, {'+','+','+'}};
78 vector<int> entrance = {1, 0};
79 cout << "output: " << Solution().nearestExit(maze, entrance) << '\n';
80 return 0;
81}
int nearestExit(vector< vector< char > > &maze, vector< int > &entrance)
Definition main.cpp:8
int main()
Definition main.cpp:73