nearest-exit-from-entrance-in-maze 1.0.0
Nearest Exit from Entrance in Maze
Loading...
Searching...
No Matches
Solution Class Reference

Public Member Functions

int nearestExit (vector< vector< char > > &maze, vector< int > &entrance)
 

Detailed Description

Definition at line 5 of file main.cpp.

Member Function Documentation

◆ nearestExit()

int Solution::nearestExit ( vector< vector< char > > &  maze,
vector< int > &  entrance 
)
inline

Definition at line 8 of file main.cpp.

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 }

Referenced by main().


The documentation for this class was generated from the following file: