3
// checks if the coordinates of the cell are that of an unvisited valid empty5
bool isValid(int x, int y, int n, int m, vector<vector<char>> &maze,6
vector<vector<int>> &visited) {7
if (x >= 0 && x < n && y >= 0 && y < m && maze[x][y] != '+' && visited[x][y] != 1) {13
// checks if the cell is a valid exit point14
bool isExit(int x, int y, int startX, int startY, vector<vector<char>> &maze,15
vector<vector<int>> &visited) {16
if (x == startX && y == startY) return false;17
if ((x == 0 || x == maze.size() - 1 || y == 0 || y == maze[0].size() - 1) &&25
int bfsHelper(vector<vector<char>> &maze, vector<vector<int>> &visited, int startX, int startY) {26
queue<vector<int>> Queue;27
Queue.push({startX, startY, 0});28
while (!Queue.empty()) {29
int x = Queue.front()[0];30
int y = Queue.front()[1];31
int steps = Queue.front()[2];33
// if you reach a valid exit, return the number of steps34
if (isExit(x, y, startX, startY, maze, visited)) return steps;35
int dx[4] = {0, -1, 0, 1};36
int dy[4] = {-1, 0, 1, 0};37
// check in the 4 directions that you can travel38
for (int i = 0; i < 4; i++) {39
int newX = x + dx[i], newY = y + dy[i];40
// if the coordinates of the cell are that of41
// an unvisited valid empty cell, add it to the queue42
// and mark it as visited.43
if (isValid(newX, newY, maze.size(), maze[0].size(), maze, visited)) {44
Queue.push({newX, newY, steps + 1});45
visited[newX][newY] = 1;49
// if you could not find a valid exit point, return -153
int nearestExit(vector<vector<char>> &maze, vector<int> &entrance) {55
int m = maze[0].size();56
// create a 2d matrix and mark all the cells as -1,57
// denoting that they have not been visited yet.58
vector<vector<int>> visited(n, vector<int>(m, -1));59
return bfsHelper(maze, visited, entrance[0], entrance[1]);