程式語言 - LeetCode - C++ - 1926. Nearest Exit from Entrance in Maze



參考資訊:
https://algo.monster/liteproblems/1926
https://www.cnblogs.com/cnoodle/p/16913967.html

題目:


解答:

class Solution {
public:
    int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
        int r = 0;
        int row = entrance[0];
        int col = entrance[1];
        int row_size = maze.size();
        int col_size = maze[0].size();
        queue<pair<int, int>> q;
        int dir[5] = { -1, 0, 1, 0, -1 };

        q.emplace(row, col);
        maze[row][col] = '+';

        while (!q.empty()) {
            int size = q.size();

            r += 1;
            for (int cnt = 0; cnt < size; cnt++) {
                auto pos = q.front();
                q.pop();

                for (int i = 0; i < 4; i++) {
                    row = pos.first + dir[i];
                    col = pos.second + dir[i + 1];

                    if ((row >= 0) && 
                        (row < row_size) && 
                        (col >= 0) && 
                        (col < col_size) &&
                        (maze[row][col] == '.'))
                    {
                        maze[row][col] = '+';
                        q.emplace(row, col);

                        if ((row == 0) ||
                            (row == (row_size - 1)) || 
                            (col == 0) ||
                            (col == (col_size - 1)))
                        {
                            return r;
                        }
                    }
                }
            }
        }

        return -1;
    }
};