class Solution 
{
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    bool visit[1010][1010] = { false };
public:
    // 多源 bfs + 最短路
    int rotApple(vector<vector<int> >&grid) {
        int n = grid.size(), m = grid[0].size();

        queue<pair<int, int>> q;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                if (grid[i][j] == 2)
                    q.push({ i,j });

        int res = 0;
        while (q.size())
        {
            res++;
            int sz = q.size(); // 一层一层出队列
            while (sz--) // 出当前层
            {
                auto [a, b] = q.front(); q.pop();
                for (int k = 0; k < 4; k++)
                {
                    int x = a + dx[k], y = b + dy[k];
                    if (x >= 0 && x < n && y >= 0 && y < m && !visit[x][y] && grid[x][y] == 1)
                    {
                        visit[x][y] = true; // 标记苹果腐烂
                        q.push({ x,y });
                    }
                }
            }

        }
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                if (!visit[i][j] && grid[i][j] == 1)
                    return -1;

        return res - 1;
    }
};