Approach
Breadth-first search
For Nearest Exit from Entrance in Maze, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 32 lines of C++ from the credited upstream file 1926.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 3 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {4 constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};5 const int m = maze.size();6 const int n = maze[0].size();7 queue<pair<int, int>> q{{{entrance[0], entrance[1]}}};8 vector<vector<bool>> seen(m, vector<bool>(n));9 seen[entrance[0]][entrance[1]] = true;10 11 for (int step = 1; !q.empty(); ++step)12 for (int sz = q.size(); sz > 0; --sz) {13 const auto [i, j] = q.front();14 q.pop();15 for (const auto& [dx, dy] : kDirs) {16 const int x = i + dx;17 const int y = j + dy;18 if (x < 0 || x == m || y < 0 || y == n)19 continue;20 if (seen[x][y] || maze[x][y] == '+')21 continue;22 if (x == 0 || x == m - 1 || y == 0 || y == n - 1)23 return step;24 q.emplace(x, y);25 seen[x][y] = true;26 }27 }28 29 return -1;30 }31};32