<p>Given an <code>m x n</code> binary matrix <code>mat</code>, return <em>the distance of the nearest </em><code>0</code><em> for each cell</em>.</p>

<p>The distance between two adjacent cells is <code>1</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/04/24/01-1-grid.jpg" style="width: 253px; height: 253px;" />
<pre>
<strong>Input:</strong> mat = [[0,0,0],[0,1,0],[0,0,0]]
<strong>Output:</strong> [[0,0,0],[0,1,0],[0,0,0]]
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/04/24/01-2-grid.jpg" style="width: 253px; height: 253px;" />
<pre>
<strong>Input:</strong> mat = [[0,0,0],[0,1,0],[1,1,1]]
<strong>Output:</strong> [[0,0,0],[0,1,0],[1,2,1]]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>m == mat.length</code></li>
	<li><code>n == mat[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li>
	<li><code>1 &lt;= m * n &lt;= 10<sup>4</sup></code></li>
	<li><code>mat[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
	<li>There is at least one <code>0</code> in <code>mat</code>.</li>
</ul>

class Solution {
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
        int rows = mat.size();
        int cols = mat[0].size();
        vector<vector<bool>>visited(rows, vector<bool>(cols));
        queue<pair<int, int>> q;
        vector<vector<int>> ans(rows, vector<int>(cols));
        int dist = 1;
        int dx[4] = {-1, 1, 0, 0};
        int dy[4] = {0, 0, -1, 1};
        for (int i=0; i<rows; i++) {
            for (int j=0; j<cols; j++) {
                if (mat[i][j] == 0) {
                    q.push({i, j});
                }
            }
        }
        while (!q.empty()) {
            vector<pair<int, int>> new_elems;
            while (!q.empty()) {
                auto [x, y] = q.front();
                q.pop();
                for (int i=0; i<4; i++) {
                    int new_x = x+dx[i];
                    int new_y = y+dy[i];
                    if (
                        new_x >= 0 && 
                        new_y >= 0 && 
                        new_x < rows && 
                        new_y < cols && 
                        mat[new_x][new_y] == 1 &&
                        !visited[new_x][new_y]
                    ) {
                        ans[new_x][new_y] = dist;
                        visited[new_x][new_y] = true;
                        new_elems.push_back({new_x, new_y});
                    }
                }
            }
            dist++;
            for (auto elem: new_elems) {
                q.push(elem);
            }
        }
        return ans;
    }
};
39876